Hướng dẫn này minh họa cách chuyển đổi chuỗi ISO 8601 thành đối tượng Date/Time trong Android sử dụng Kotlin.
Bước 1: Tạo dự án mới
Mở Android Studio, chọn File → New Project và điền thông tin cần thiết.
Bước 2: Thiết kế giao diện (activity_main.xml)
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dp"
android:text="Tutorials Point"
android:textAlignment="center"
android:textColor="@android:color/holo_green_dark"
android:textSize="32sp"
android:textStyle="bold" />
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:textAlignment="center"
android:textColor="@android:color/holo_red_dark"
android:textSize="24sp"
android:textStyle="bold" />
</RelativeLayout>
Bước 3: Viết code MainActivity.kt (Cách cũ - Java SimpleDateFormat)
import android.os.Bundle
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import java.text.SimpleDateFormat
import java.util.*
class MainActivity : AppCompatActivity() {
lateinit var textView: TextView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
title = "KotlinApp"
textView = findViewById(R.id.textView)
val dtStart = "2020-07-05T09:27:37Z"
val format = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'")
format.timeZone = TimeZone.getTimeZone("UTC")
val date: Date = format.parse(dtStart)
textView.text = "ISO 8601 date/time: $date"
}
}
Cách hiện đại: java.time (API 26+ / Android 8.0+)
import java.time.Instant
import java.time.ZoneId
import java.time.ZonedDateTime
import java.time.format.DateTimeFormatter
class MainActivity : AppCompatActivity() {
// ...
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// ...
val isoString = "2020-07-05T09:27:37Z"
// Parse ISO 8601 trực tiếp (ISO_INSTANT format)
val instant = Instant.parse(isoString)
// Chuyển về múi giờ thiết bị
val zonedDateTime = instant.atZone(ZoneId.systemDefault())
// Format hiển thị
val formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss z")
textView.text = "ISO 8601: ${zonedDateTime.format(formatter)}"
// Hoặc giữ UTC
val utcTime = instant.atZone(ZoneId.of("UTC"))
textView.text = "UTC: ${utcTime.format(formatter)}"
}
}
Cách dùng ThreeTenABP (Android API < 26)
Thêm dependency trong build.gradle:
implementation "org.threeten:threetenbp:1.6.8" // Khởi tạo trong Application class import org.threeten.bp.AndroidThreeTen AndroidThreeTen.init(this)
Sau đó dùng org.threeten.bp.* thay vì java.time.*.
Bước 4: Cấu hình AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
package="com.example.q11">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
</intent-filter>
</activity>
</application>
</manifest>
Chạy ứng dụng
Kết nối thiết bị, nhấn Run. TextView hiển thị ngày giờ đã parse từ chuỗi ISO 8601.
So sánh các cách parse ISO 8601
| Cách | API Level | Ưu điểm | Nhược điểm |
|---|---|---|---|
SimpleDateFormat | Tất cả | Tương thích ngược | Không thread-safe, deprecated Java 8+ |
java.time.Instant.parse() | 26+ | Chuẩn ISO, thread-safe, immutable | Yêu cầu API 26+ hoặc ThreeTenABP |
DateTimeFormatter.ISO_INSTANT | 26+ | Format chuẩn ISO 8601 | Cần API 26+ |
Gson/Moshi/Jackson | Tất cả | Tự động parse khi deserialize JSON | Cần library thêm |
Các định dạng ISO 8601 phổ biến
2020-07-05T09:27:37Z- UTC (Z = Zulu time)2020-07-05T09:27:37+07:00- Có offset múi giờ2020-07-05T09:27:37.123Z- Có milliseconds2020-07-05- Chỉ ngày
Best practice: Luôn lưu trữ và truyền dữ liệu ở UTC (ISO 8601 với Z). Chỉ convert sang local timezone khi hiển thị cho user.