Problem

If you need to get the current date in different formats using java 8 you have several options.

Solution Use LocalDate, LocalDateTime, or ZonedDateTime(Java 8)

Several notes on the code snippet below:

  • you need to set the Date to Calendar by calling setTime() method
  • months are 0 based - so 0 is January and 11 is December
    Those issues are addressed in Java 8
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.Month;

LocalDate currentDate = LocalDate.now(); // 2018-01-28
DayOfWeek dow = currentDate.getDayOfWeek(); // SUNDAY
int dom = currentDate.getDayOfMonth(); // 28
int doy = currentDate.getDayOfYear(); // 28
Month m = currentDate.getMonth(); // JANUARY
int y = currentDate.getYear(); // 2018

System.out.println("current local date : " + currentDate);
System.out.println("dayOfWeek: " + dow);
System.out.println("dayOfMonth " + dom);
System.out.println("dayOfYear : " + doy);
System.out.println("month " + m);
System.out.println("year : " + y);

Solution Use java.util.Calendar (Java 5,6 compatible)

Several notes on the code snippet below:

  • you need to set the Date to Calendar by calling setTime() method
  • months are 0 based - so 0 is January and 11 is December
    Those issues are addressed in Java 8
Date today = new Date(); // Sun Jan 28 21:03:19 EET 2018
Calendar cal = Calendar.getInstance();
cal.setTime(today); // don't forget this if date is arbitrary e.g. 01-01-2014

int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK); // 1
int dayOfMonth = cal.get(Calendar.DAY_OF_MONTH); // 28
int dayOfYear = cal.get(Calendar.DAY_OF_YEAR); //28

int month = cal.get(Calendar.MONTH); // 0
int year = cal.get(Calendar.YEAR); // 2018