Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Android

Cách hiển thị ngày giờ hiện tại trong ứng dụng Android?

Giới thiệu

Bài viết minh họa cách lấy và hiển thị ngày giờ hiện tại của hệ thống trên Android sử dụng java.text.DateFormat và java.util.Date.

Các bước thực hiện

Bước 1: Tạo dự án mới

Khởi tạo project Android Studio.

Bước 2: Giao diện TextView (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>

Bước 3: Logic lấy ngày giờ (src/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);
        String currentDateTimeString = DateFormat.getDateTimeInstance().format(new Date());
        tvDateTime.setText(currentDateTimeString);
    }
}

Bước 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>

Chạy ứng dụng

Kết nối thiết bị, nhấn Run. TextView hiển thị ngày giờ hiện tại theo locale của thiết bị (ví dụ: "Thứ 2, 15 tháng 3, 2024 14:30:25").

Cách hiển thị ngày giờ hiện tại trong ứng dụng Android?

Tùy chỉnh định dạng ngày giờ

1. Dùng SimpleDateFormat (cũ, không thread-safe)

SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss", Locale.getDefault());
String formatted = sdf.format(new Date()); // "15/03/2024 14:30:25"

2. Dùng DateTimeFormatter (Java 8+, API 26+ - khuyên dùng)

// Cần minSdkVersion 26 hoặc bật coreLibraryDesugaring
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss")
    .withLocale(Locale.getDefault())
    .withZone(ZoneId.systemDefault());
String formatted = formatter.format(Instant.now());

3. Các mẫu pattern phổ biến

  • dd/MM/yyyy - 15/03/2024
  • EEEE, dd MMMM yyyy - Thứ Hai, 15 Tháng Ba 2024
  • HH:mm:ss - 14:30:25 (24h)
  • hh:mm a - 02:30 PM (12h)
  • yyyy-MM-dd'T'HH:mm:ssZ - ISO 8601: 2024-03-15T14:30:25+0700

4. Cập nhật real-time (đồng hồ chạy)

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); // Cập nhật mỗi giây
    }
};
handler.post(updateTime);

// Trong onDestroy: handler.removeCallbacks(updateTime);

Lưu ý

  • DateFormat.getDateTimeInstance() tự động dùng locale/múi giờ của thiết bị
  • Tránh tạo SimpleDateFormat trong vòng lặp/onDraw (tốn hiệu suất)
  • Android 7.0+ (API 24) hỗ trợ Java 8 Time API (java.time.*) qua desugaring
  • Để hiển thị múi giờ khác: dùng TimeZone hoặc ZoneId