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

Cách lấy ngày hiện tại trong Android dùng LocalDate API

Giới thiệu

Từ Android API 26 (Oreo), Java 8 Date/Time API (java.time.LocalDate) khả dụng. Bài viết demo lấy ngày hôm nay, hôm qua, ngày mai.

Các bước

Bước 1: Tạo project

File → New Project → Empty Activity.

Bước 2: 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"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/date"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Ngày địa phương"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

Bước 3: MainActivity.java

package com.example.myapplication;

import android.os.Build;
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.date);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            LocalDate today = LocalDate.now();
            LocalDate yesterday = today.minusDays(1);
            LocalDate tomorrow = today.plusDays(1);

            textView.setText("Hôm nay: " + today + "\nHôm qua: " + yesterday + "\nNgày mai: " + tomorrow);
        }
    }
}

Giải thích

  • LocalDate.now(): ngày hiện tại theo múi giờ mặc định.
  • minusDays(1) / plusDays(1): trừ/cộng ngày.
  • Yêu cầu minSdkVersion 26 hoặc bật coreLibraryDesugaringEnabled true trong build.gradle để dùng trên API thấp hơn.

Kết quả

Cách lấy ngày hiện tại trong Android dùng LocalDate API

TextView hiển thị ba ngày: hôm nay, hôm qua, ngày mai. Có thể so sánh với ngày hệ thống để kiểm tra.