Giới thiệu
Ví dụ này minh họa cách lấy cả ngày và giờ hiện tại trong Android sử dụng LocalDateTime và DateTimeFormatter (yêu cầu API level 26+).
Bước 1: Tạo project mới
Mở Android Studio, chọn File → New Project, điền thông tin cần thiết.
Bước 2: Thiết kế giao diện (res/layout/activity_main.xml)
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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/date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Ngày & Giờ địa phương"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
Bước 3: Code MainActivity.java
package com.example.myapplication;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView textView = findViewById(R.id.date);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
LocalDateTime dateTime = LocalDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss");
String formatted = dateTime.format(formatter);
textView.setText("Ngày & Giờ: " + formatted);
}
}
}
Giải thích:
LocalDateTime.now()lấy ngày giờ hiện tại theo múi giờ thiết bị.DateTimeFormatter.ofPattern(...)định dạng chuỗi đầu ra (ngày-tháng-năm giờ:phút:giây).- Phương thức
format()trả về chuỗi đã định dạng.
Chạy ứng dụng
Kết nối thiết bị, nhấn Run. Màn hình hiển thị ngày và giờ hiện tại theo định dạng đã chỉ định.
