Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Android

วิธีแสดงวันที่และเวลาปัจจุบันในแอป Android

การแสดงวันที่และเวลาปัจจุบันด้วย DateFormat และ Date

ตัวอย่างนี้แสดงวิธีดึงวันที่/เวลาปัจจุบันจากระบบ และจัดรูปแบบให้อ่านง่ายด้วย DateFormat.getDateTimeInstance()

ขั้นตอนที่ 1: สร้างโปรเจกต์ใหม่

Android Studio → File → New Project → กรอกรายละเอียด → Finish

ขั้นตอนที่ 2: Layout - res/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"
    tools:context=".MainActivity">
    <TextView
        android:id="@+id/tvDateTime"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:layout_margin="16dp"
        android:gravity="center"
        android:padding="16dp"
        android:textSize="24sp" />
</RelativeLayout>

ขั้นตอนที่ 3: MainActivity.java

package app.com.sample;

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import java.text.DateFormat;
import java.util.Date;

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        TextView tvDateTime = findViewById(R.id.tvDateTime);
        
        // ดึงวันที่/เวลาปัจจุบันและจัดรูปแบบตาม Locale ของระบบ
        String currentDateTimeString = DateFormat.getDateTimeInstance().format(new Date());
        tvDateTime.setText(currentDateTimeString);
    }
}

ขั้นตอนที่ 4: AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="app.com.sample">
    <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>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

รูปแบบ DateFormat ต่างๆ

Methodตัวอย่างผลลัพธ์ (th_TH)คำอธิบาย
getDateTimeInstance()1 มกราคม 2567 14:30:00วันที่และเวลาแบบเต็ม
getDateInstance()1 มกราคม 2567เฉพาะวันที่
getTimeInstance()14:30:00เฉพาะเวลา
getDateTimeInstance(SHORT, SHORT)1/1/2567 14:30สั้น
getDateTimeInstance(MEDIUM, MEDIUM)1 ม.ค. 2567 14:30:00ปานกลาง
getDateTimeInstance(LONG, LONG)1 มกราคม 2567 14:30:00 น.ยาว
getDateTimeInstance(FULL, FULL)วันจันทร์ที่ 1 มกราคม 2567 14:30:00 น. ICTเต็มรูปแบบ

ใช้ SimpleDateFormat สำหรับ Custom Format

// รูปแบบไทย
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss", new Locale("th", "TH"));
String formatted = sdf.format(new Date());
// ผลลัพธ์: 01/01/2567 14:30:00

// Pattern ตัวอักษรสำคัญ
// y = ปี, M = เดือน, d = วัน, H = ชั่วโมง (24h), h = ชั่วโมง (12h)
// m = นาที, s = วินาที, a = AM/PM, E = วันในสัปดาห์

Java 8+ Time API (แนะนำสำหรับ API 26+)

// ต้องเพิ่ม coreLibraryDesugaringEnabled true ใน build.gradle
LocalDateTime now = LocalDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss", new Locale("th", "TH"));
String formatted = now.format(formatter);

// ใช้ ZoneId สำหรับ Timezone
ZonedDateTime zdt = ZonedDateTime.now(ZoneId.of("Asia/Bangkok"));

การอัปเดตเวลา Real-time

// ใช้ Handler อัปเดตทุกวินาที
Handler handler = new Handler(Looper.getMainLooper());
Runnable updateTime = new Runnable() {
    @Override
    public void run() {
        tvDateTime.setText(DateFormat.getDateTimeInstance().format(new Date()));
        handler.postDelayed(this, 1000);
    }
};
handler.post(updateTime);

// อย่าลืม removeCallbacks ใน onDestroy()
@Override
protected void onDestroy() {
    handler.removeCallbacks(updateTime);
    super.onDestroy();
}

การทดสอบ

รันแอป → จะแสดงวันที่และเวลาปัจจุบันตรงกลางหน้าจอ ตามรูปแบบ Locale ของเครื่อง