How to get current day, month and year in Java 8?


The java.time package of Java provides API’s for dates, times, instances and durations. It provides various classes like Clock, LocalDate, LocalDateTime, LocalTime, MonthDay,Year, YearMonth etc. Using classes of this package you can get details related to date and time in much simpler way compared to previous alternatives.

Java.time.LocalDate − This class represents a date object without time zone in ISO-8601 calendar system. The now() method of this class obtains the current date from the system clock.

This class also provides various other useful methods among them −

  • The getYear() method returns an integer representing the year filed in the current LocalDate object.
  • The getMonth() method returns an object of the java.timeMonth class representing the month in the LocalDate object.
  • The getDaYofMonth() method returns an integer representing the day in the LocalDate object.

Example

Following Java example retrieves the current date and prints the day, year and, month separately using the above specified methods.

import java.time.LocalDate;
import java.time.Month;
public class LocalDateJava8 {
   public static void main(String args[]) {
      //Getting the current date value
      LocalDate currentdate = LocalDate.now();
      System.out.println("Current date: "+currentdate);
      //Getting the current day
      int currentDay = currentdate.getDayOfMonth();
      System.out.println("Current day: "+currentDay);
      //Getting the current month
      Month currentMonth = currentdate.getMonth();
      System.out.println("Current month: "+currentMonth);
      //getting the current year
      int currentYear = currentdate.getYear();
      System.out.println("Current month: "+currentYear);
   }
}

Output

Current date: 2019-07-24
Current day: 24
Current month: JULY
Current month: 2019
raja
Published on 07-Aug-2019 14:32:18
Advertisements