บทนำ: java.time.LocalDate ใน Android
ตั้งแต่ Android API 26 (Oreo) สามารถใช้ java.time.LocalDate จาก Java 8 Time API ได้ ซึ่งเป็นวิธีที่ทันสมัยและแนะนำสำหรับจัดการวันที่ ไม่ต้องใช้ Calendar/Date เก่าๆ
ตัวอย่าง: แสดงวันนี้ เมื่อวาน และพรุ่งนี้
ขั้นตอนที่ 1: สร้างโปรเจกต์ใหม่
Android Studio → File → New Project → เลือก Empty Activity → Finish
ขั้นตอนที่ 2: Layout (res/layout/activity_main.xml)
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:app="https://schemas.android.com/apk/res-auto"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/dateTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Local Date"
android:textSize="18sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
ใช้ 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.LocalDate;
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);
// ตรวจสอบ API Level 26+ (Android 8.0 Oreo)
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
LocalDate today = LocalDate.now();
LocalDate yesterday = today.minusDays(1);
LocalDate tomorrow = today.plusDays(1);
String result = "Today: " + today + "\n" +
"Yesterday: " + yesterday + "\n" +
"Tomorrow: " + tomorrow;
textView.setText(result);
} else {
textView.setText("ต้องการ Android 8.0 (API 26) ขึ้นไป");
}
}
}
คำอธิบาย API สำคัญ
| เมธอด | คำอธิบาย | ตัวอย่างผลลัพธ์ |
|---|---|---|
LocalDate.now() | วันที่ปัจจุบันตาม Timezone ของอุปกรณ์ | 2024-01-15 |
minusDays(n) | ลบ n วัน | 2024-01-14 |
plusDays(n) | บวก n วัน | 2024-01-16 |
minusWeeks(n) | ลบ n สัปดาห์ | - |
plusMonths(n) | บวก n เดือน | - |
getDayOfWeek() | วันในสัปดาห์ (MONDAY-SUNDAY) | MONDAY |
getDayOfMonth() | วันที่ในเดือน (1-31) | 15 |
getDayOfYear() | วันที่ในปี (1-366) | 15 |