ภาพรวม
ตัวอย่างนี้สาธิตวิธีแปลงสตริงวันที่รูปแบบ ISO 8601 (เช่น "2019-08-15T09:27:37Z") ให้เป็นอ็อบเจกต์ Date ใน Java/Android
ขั้นตอนที่ 1: สร้างโปรเจกต์ใหม่
สร้างโปรเจกต์ Android ใหม่ใน Android Studio
ขั้นตอนที่ 2: จัดทำ Layout (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"
android:gravity="center"
tools:context=".MainActivity">
<TextView
android:id="@+id/textView"
android:padding="20sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:textSize="12sp"
android:textStyle="bold"/>
</RelativeLayout>
ขั้นตอนที่ 3: เขียนโค้ด MainActivity.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class MainActivity extends AppCompatActivity {
TextView textView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.textView);
String dtStart = "2019-08-15T09:27:37Z";
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
try {
Date date = format.parse(dtStart);
textView.setText("ISO 8601 date/time: " + date);
} catch (ParseException e) {
e.printStackTrace();
}
}
}
รูปแบบวันที่ ISO 8601 ที่พบบ่อย
| รูปแบบ | Pattern | ตัวอย่าง |
|---|---|---|
| UTC (Zulu) | yyyy-MM-dd'T'HH:mm:ss'Z' | 2019-08-15T09:27:37Z |
| มี Timezone Offset | yyyy-MM-dd'T'HH:mm:ssXXX | 2019-08-15T09:27:37+07:00 |
| มีมิลลิวินาที | yyyy-MM-dd'T'HH:mm:ss.SSS'Z' | 2019-08-15T09:27:37.123Z |
หมายเหตุสำคัญ
- SimpleDateFormat ไม่ thread-safe ควรสร้าง instance ใหม่ทุกครั้ง
- Android API 26+ แนะนำให้ใช้
java.time(DateTimeFormatter) - Pattern ต้องตรงกับสตริงนำเข้าทุกตัวอักษร รวมถึง 'T' และ 'Z'
วิธีใหม่ (API 26+)
// ใช้ java.time สำหรับ Android 8.0+
DateTimeFormatter formatter = DateTimeFormatter.ISO_INSTANT;
Instant instant = Instant.parse("2019-08-15T09:27:37Z");
ZonedDateTime zdt = instant.atZone(ZoneId.systemDefault());
การทดสอบ
รันแอป จะแสดงวันที่และเวลาที่แปลงแล้วใน TextView