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

Cách lấy ngày trong tháng, ngày trong năm, ngày trong tuần dùng OffsetDateTime API

Giới thiệu

java.time.OffsetDateTime (API 26+) cung cấp đầy đủ thông tin ngày giờ có múi giờ. Demo lấy day-of-month, day-of-year, day-of-week.

Các bước

Bước 1 & 2: Project & Layout

Layout: một 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.OffsetDateTime;

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) {
            OffsetDateTime now = OffsetDateTime.now();
            String info = "Ngày trong tuần: " + now.getDayOfWeek() +
                    "\nNgày trong tháng: " + now.getDayOfMonth() +
                    "\nNgày trong năm: " + now.getDayOfYear();
            textView.setText(info);
        }
    }
}

Giải thích

  • getDayOfWeek(): trả về enum DayOfWeek (MONDAY, TUESDAY...).
  • getDayOfMonth(): 1-31.
  • getDayOfYear(): 1-365/366.
  • Cần API 26+.

Kết quả

Cách lấy ngày trong tháng, ngày trong năm, ngày trong tuần dùng OffsetDateTime API

Hiển thị thứ, ngày tháng, ngày năm hiện tại.