บทนำ: java.time.OffsetTime ใน Android
OffsetTime เป็นคลาสใน Java 8 Time API (API 26+) ที่แสดงเวลาพร้อม Offset จาก UTC เหมาะสำหรับงานที่ต้องการเวลาพร้อมข้อมูล Timezone
ตัวอย่าง: แสดงเวลาปัจจุบัน (ชั่วโมง:นาที:วินาที)
ขั้นตอนที่ 1: สร้างโปรเจกต์
Android Studio → New Project → Empty Activity
ขั้นตอนที่ 2: Layout (activity_main.xml)
TextView เดียวใน ConstraintLayout จัดกึ่งกลาง (เหมือนตัวอย่างก่อนหน้า)
ขั้นตอนที่ 3: MainActivity.java
package com.example.myapplication;
import android.os.Bundle;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import java.time.OffsetTime;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView textView = findViewById(R.id.dateTextView);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
OffsetTime offsetTime = OffsetTime.now();
int hour = offsetTime.getHour(); // 0-23
int minute = offsetTime.getMinute(); // 0-59
int second = offsetTime.getSecond(); // 0-59
int nano = offsetTime.getNano(); // 0-999,999,999
String timeString = String.format("%02d:%02d:%02d", hour, minute, second);
textView.setText("Current Time: " + timeString + "\nOffset: " + offsetTime.getOffset());
} else {
textView.setText("ต้องการ Android 8.0 (API 26) ขึ้นไป");
}
}
}
คำอธิบาย OffsetTime สำคัญ
| เมธอด | คำอธิบาย |
|---|---|
now() | เวลาปัจจุบันพร้อม Offset ของ System Default Zone |
now(ZoneId zone) | เวลาปัจจุบันใน Zone ที่ระบุ |
getHour() | ชั่วโมง (0-23) |
getMinute() | นาที (0-59) |
getSecond() | วินาที (0-59) |
getNano() | นาโนวินาที (0-999,999,999) |
getOffset() | ZoneOffset (เช่น +07:00) |
toLocalTime() | แปลงเป็น LocalTime (ไม่มี Offset) |
OffsetTime vs LocalTime vs ZonedDateTime
- LocalTime: เวลาเพียงอย่างเดียว ไม่มี Timezone/Offset
- OffsetTime: เวลา + Offset (เช่น 14:30+07:00) ไม่มี Zone Rules
- ZonedDateTime: วันเวลา + Zone ID (มี DST rules, เหมาะสำหรับแอปทั่วโลก)
การรองรับ API ต่ำกว่า 26
เพิ่มใน build.gradle (เหมือนตัวอย่าง LocalDate):
coreLibraryDesugaringEnabled true
dependencies {
coreLibraryDesugaring "com.android.tools:desugar_jdk_libs:1.2.2"
}
ผลลัพธ์
Current Time: 14:30:45 Offset: +07:00
การประยุกต์ใช้
- แสดงเวลาปัจจุบันพร้อม Timezone
- บันทึก Log/Event พร้อม Offset เพื่อความแม่นยำ
- Sync กับ Server ที่ต้องการ Offset