Một trường thời gian (temporal field) là một trường của ngày-giờ, chẳng hạn như tháng-trong-năm hoặc giờ-trong-phút. Các trường này được biểu diễn bởi interface TemporalField và lớp ChronoField triển khai interface này.
Phương thức get() hoặc getLong() của lớp LocalDateTime chấp nhận một trường thời gian làm tham số và lấy giá trị của trường đó trong đối tượng hiện tại.
Ví dụ 1: Truy xuất các trường liên quan đến ngày
Ví dụ sau lấy giá trị của các trường thời gian liên quan đến ngày từ một đối tượng LocalDateTime.
import java.time.LocalDateTime;
import java.time.temporal.ChronoField;
public class Demo {
public static void main(String args[]) {
// Khởi tạo lớp LocalDateTime
LocalDateTime lDate = LocalDateTime.now();
int field = lDate.get(ChronoField.DAY_OF_MONTH);
System.out.println("Ngày của tháng: " + field);
field = lDate.get(ChronoField.DAY_OF_WEEK);
System.out.println("Ngày của tuần: " + field);
field = lDate.get(ChronoField.DAY_OF_YEAR);
System.out.println("Ngày của năm: " + field);
long epoch = lDate.getLong(ChronoField.EPOCH_DAY);
System.out.println("Ngày epoch: " + epoch);
field = lDate.get(ChronoField.ALIGNED_DAY_OF_WEEK_IN_MONTH);
System.out.println("Tuần trong tháng: " + field);
field = lDate.get(ChronoField.ALIGNED_DAY_OF_WEEK_IN_YEAR);
System.out.println("Ngày của tuần trong năm: " + field);
field = lDate.get(ChronoField.ERA);
System.out.println("Kỷ nguyên: " + field);
}
}
Kết quả
Ngày của tháng: 25 Ngày của tuần: 5 Ngày của năm: 237 Ngày epoch: 17403 Tuần trong tháng: 4 Ngày của tuần trong năm: 6 AM hoặc PM: 6 Kỷ nguyên: 1
Ví dụ 2: Truy xuất các trường liên quan đến giờ
Ví dụ sau lấy giá trị của các trường thời gian liên quan đến giờ từ một đối tượng LocalDateTime.
import java.time.Clock;
import java.time.LocalDateTime;
import java.time.temporal.ChronoField;
public class CreateDateTime {
public static void main(String args[]) {
// Khởi tạo lớp LocalDateTime
LocalDateTime lDateTime = LocalDateTime.now();
System.out.println(lDateTime);
int field = lDateTime.get(ChronoField.CLOCK_HOUR_OF_AMPM);
System.out.println("Giờ của ngày (AM/PM): " + field);
field = lDateTime.get(ChronoField.AMPM_OF_DAY);
System.out.println("AM hoặc PM: " + field);
field = lDateTime.get(ChronoField.CLOCK_HOUR_OF_DAY);
System.out.println("Giờ của ngày (1-24): " + field);
long epoch = lDateTime.getLong(ChronoField.MINUTE_OF_DAY);
System.out.println("Phút của ngày: " + epoch);
field = lDateTime.get(ChronoField.MINUTE_OF_HOUR);
System.out.println("Phút của giờ: " + field);
field = lDateTime.get(ChronoField.SECOND_OF_DAY);
System.out.println("Giây của ngày: " + field);
field = lDateTime.get(ChronoField.SECOND_OF_MINUTE);
System.out.println("Giây của phút: " + field);
}
}
Kết quả
2020-11-11T14:58:22.680 Giờ của ngày (AM/PM): 2 AM hoặc PM: 1 Giờ của ngày (1-24): 14 Phút của ngày: 898 Phút của giờ: 58 Giây của ngày: 53902 Giây của phút: 22