Giới thiệu
java.time.YearMonth (API 26+) biểu diễn năm-tháng (không ngày). Demo lấy năm-tháng hiện tại.
Các bước
Bước 1 & 2: Project & Layout
Layout: TextView (id: date) trong 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.YearMonth;
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) {
YearMonth ym = YearMonth.now();
textView.setText("Năm-Tháng: " + ym); // định dạng 2024-01
}
}
}
Giải thích
YearMonth.now(): năm-tháng hiện tại theo múi giờ mặc định.- toString() trả về định dạng ISO:
YYYY-MM(ví dụ: 2024-01). - Có thể dùng
getYear(),getMonthValue(),lengthOfMonth()(số ngày trong tháng).
Kết quả

Hiển thị "Năm-Tháng: 2024-01".