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

Cách lấy giờ, phút, giây trong Android dùng OffsetTime API

Giới thiệu

java.time.OffsetTime (API 26+) biểu diễn thời gian có múi giờ offset. Ví dụ lấy giờ, phút, giây hiện tại.

Các bước

Bước 1 & 2: Project & Layout

Layout chỉ chứa 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.OffsetTime;

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) {
            OffsetTime now = OffsetTime.now();
            String time = now.getHour() + " : " + now.getMinute() + " : " + now.getSecond();
            textView.setText(time);
        }
    }
}

Giải thích

  • OffsetTime.now(): lấy thời gian hiện tại kèm offset múi giờ.
  • getHour(), getMinute(), getSecond(): trích xuất thành phần giờ/phút/giây.
  • Cần API 26+ hoặc desugaring.

Kết quả

Cách lấy giờ, phút, giây trong Android dùng OffsetTime API

Hiển thị định dạng "Giờ : Phút : Giây" (ví dụ: 14 : 30 : 45).