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

Định dạng ngày giờ trong Android bằng Kotlin

Giới thiệu

Ví dụ này minh họa cách định dạng ngày và giờ hiện tại theo mẫu tùy chỉnh sử dụng SimpleDateFormat (hoặc DateTimeFormatter hiện đại) trong Android Kotlin.

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

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

Mở Android Studio, chọn File → New Project, điền thông tin.

Bước 2: Giao diện (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:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="50dp"
        android:text="Tutorials Point"
        android:textAlignment="center"
        android:textColor="@android:color/holo_green_dark"
        android:textSize="32sp"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:textAlignment="center"
        android:textColor="@android:color/black"
        android:textSize="16sp"
        android:textStyle="bold|italic" />

</RelativeLayout>

Bước 3: MainActivity.kt (cách hiện đại với java.time)

import android.os.Bundle
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
import java.util.Locale

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        title = "KotlinApp"

        val textView = findViewById<TextView>(R.id.textView)

        // Cách hiện đại (API 26+): dùng java.time
        val now = LocalDateTime.now()
        val formatter = DateTimeFormatter.ofPattern("EEEE, dd-MMM-yyyy hh:mm:ss a", Locale.getDefault())
        val dateTime = now.format(formatter)

        textView.text = dateTime
    }
}

Lưu ý: java.time yêu cầu minSdkVersion 26 hoặc bật coreLibraryDesugaringEnabled true trong build.gradle để hỗ trợ API thấp hơn.

Cách cũ (SimpleDateFormat):

import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Locale

val calendar = Calendar.getInstance()
val sdf = SimpleDateFormat("EEEE, dd-MMM-yyyy hh:mm:ss a", Locale.getDefault())
val dateTime = sdf.format(calendar.time)
textView.text = dateTime

Bước 4: AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="com.example.q11">

    <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. Màn hình hiển thị ngày giờ hiện tại theo định dạng "Thứ, dd-MMM-yyyy hh:mm:ss AM/PM".