Java Date Time API: LocalDateTime get(TemporalField field) examples


Java Date Time get method examples

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,

  1. Get the Year

    int year = localDateTime.get(ChronoField.YEAR);
    System.out.println("Year : " + year);
    
    //Output: 2022
  2. Get the Month of the Year

    int monthOfYear = localDateTime.get(ChronoField.MONTH_OF_YEAR);
    System.out.println("Day of the Month: " + monthOfYear);
    
    //Output: 5
  3. Get the Day of the Month

    int monthOfYear = localDateTime.get(ChronoField.MONTH_OF_YEAR);
    System.out.println("Day of the Month: " + monthOfYear);
    
    //Output: 14
  4. Get the Hour of the Day

    int hourOfDay = localDateTime.get(ChronoField.HOUR_OF_DAY);
    System.out.println("Hour of the Day : " + hourOfDay);
    
    //Output: 9
  5. Get the Minutes of the Hour

    int minuteOfHour = localDateTime.get(ChronoField.MINUTE_OF_HOUR);
    System.out.println("Minute of the Hour : " + minuteOfHour);
    
    //Output: 27
  6. Get the Seconds of the Minute

    int secondOfMinute = localDateTime.get(ChronoField.SECOND_OF_MINUTE);
    System.out.println("Second of the Minute : " + secondOfMinute);
    
    //Output: 38
  7. Get 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,

  1. Get the Seconds of the Day

    int secondOfDay = localDateTime.get(ChronoField.SECOND_OF_DAY);
    System.out.println("Seconds of Day : " + secondOfDay);
    
    //Output: 96024
  2. Get the Day of the Year

    int dayOfYear = localDateTime.get(ChronoField.DAY_OF_YEAR);
    System.out.println("Day of the Year : " + dayOfYear);
    
    //Output: 134
  3. Get the Seconds of the Minute

    int secondOfMinute = localDateTime.get(ChronoField.SECOND_OF_MINUTE);
    System.out.println("Second of the Minute : " + secondOfMinute);
    
    //Output: 38
  4. Get the AM/PM of the Day

    //AM=0 PM=1
    int AmorPM = localDateTime.get(ChronoField.AMPM_OF_DAY);
    System.out.println(AmorPM);
    
    //Output: 0


















Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap