
The get(TemporalField field) method from LocalDateTime can be used to get the value of the specified field from the current object as an integer. Let's take a look at some of the examples of how to use it,
LocalDateTime localDateTime = LocalDateTime.now(ZoneId.of("UTC"));
System.out.println("Current Date Time (UTC/GMT): " + localDateTime);
Current Date Time (UTC/GMT): 2022-05-14T09:27:38.319137
We have a LocalDateTime object in Zone UTC and now we are going to make use of the get(TemporalField field) methods over it to get various fields from it,
Get the Year
int year = localDateTime.get(ChronoField.YEAR); System.out.println("Year : " + year); //Output: 2022Get the Month of the Year
int monthOfYear = localDateTime.get(ChronoField.MONTH_OF_YEAR); System.out.println("Day of the Month: " + monthOfYear); //Output: 5Get the Day of the Month
int monthOfYear = localDateTime.get(ChronoField.MONTH_OF_YEAR); System.out.println("Day of the Month: " + monthOfYear); //Output: 14Get the Hour of the Day
int hourOfDay = localDateTime.get(ChronoField.HOUR_OF_DAY); System.out.println("Hour of the Day : " + hourOfDay); //Output: 9Get the Minutes of the Hour
int minuteOfHour = localDateTime.get(ChronoField.MINUTE_OF_HOUR); System.out.println("Minute of the Hour : " + minuteOfHour); //Output: 27Get the Seconds of the Minute
int secondOfMinute = localDateTime.get(ChronoField.SECOND_OF_MINUTE); System.out.println("Second of the Minute : " + secondOfMinute); //Output: 38Get the Seconds of the Minute
int millSecOfSecond = localDateTime.get(ChronoField.MILLI_OF_SECOND); System.out.println("Mill-second of the Second : " + millSecOfSecond); //Output: 319137
Now let's look at some more fields that are not displayed as a part of the default LocalDateTime toString output,
Get the Seconds of the Day
int secondOfDay = localDateTime.get(ChronoField.SECOND_OF_DAY); System.out.println("Seconds of Day : " + secondOfDay); //Output: 96024Get the Day of the Year
int dayOfYear = localDateTime.get(ChronoField.DAY_OF_YEAR); System.out.println("Day of the Year : " + dayOfYear); //Output: 134Get the Seconds of the Minute
int secondOfMinute = localDateTime.get(ChronoField.SECOND_OF_MINUTE); System.out.println("Second of the Minute : " + secondOfMinute); //Output: 38Get the AM/PM of the Day
//AM=0 PM=1 int AmorPM = localDateTime.get(ChronoField.AMPM_OF_DAY); System.out.println(AmorPM); //Output: 0
Provide Feedback For This Article
We take your feedback seriously and use it to improve our content. Thank you for helping us serve you better!
😊 Thanks for your time, your feedback has been registered!
Comments & Discussion
Facing issues? Have questions? Post them here! We're happy to help!