How to get current Day, Month, Year from Date in Java 8 and before? LocalDate vs java.util.Date

In this article, I'll show you how to get the current day, month, year, and dayOfWeek in Java 8 and earlier version e.g. Java 6 and JDK 1.7. Prior to Java 8, you can use the Calendar class to get the various attribute from java.util.Date in Java. The Calendar class provides a get() method which accepts an integer field corresponding to the attribute you want to extract and return the value of the field from given Date, as shown here. You might be wondering, why not use the getMonth() and getYear() method of java.util.Date itself, well, they are deprecated and can be removed in the future version, hence it is not advised to use them. The key point is, using old Date and Calendar API is not easy, it's very difficult to reason and debug code written using Calendar API, as it uses integer value instead of Enum or String. So, when you print e.g. Month, it will print 0 (Zero which may look wrong, but it's the value for January in old Date and Calendar API.


Things are much better in Java 8, as it introduces new Date and Time API. Here you can use the LocalDate class from java.time package to represent a date. This class also has several get methods to retrieve different date related attribute e.g. getDayOfWeek() will return Day of the week, getMonth() will return Month, and getYear() will return year. The good thing about Java 8 Date API is that you don't need to use any additional class like Calendar to extract date fields e.g. month and year.


Another good thing about java.time API is that it uses Enum for Month and DayOfWeek, which means a more meaningful and correct value is printed when you pass the output to System.out.println() or log into your log file. Don't underestimate the value of this feature because it makes debugging quite easy.

You don't need to guess if 5 is May or June in a huge log file while searching for a missing order. This is also the reason why Joshua Bloch advised to "use Enum over int pattern" to represent fixed number of things in his all time classic book Effective Java. It makes the output more readable and debugging easier.



How to get Day, Month and Year in Java 6,7

As I said you can use the java.util.Calendar class to extract month, year, day, dayOfMonth, dayOfWeek, and dayOfYear from a given Date in Java. You can get the Calendar instance local to your system and time zone by calling the Calendar.getInstance() method.


Once you get that, you need to set the Date to Calendar by calling setTime() method. It's one of the common mistakes in Java to forget setting Date to Calendar, which leads to incorrect output and subtle bugs. There is no compile time error because by default Calendar is set to the current date in Java.

Once you got a Calendar instance, you can extract any date related or time-related field by using get() method, which takes an int value, denoting the constant defined in Calendar for that field e.g. Month, Year, or DayOfWeek as shown in the following example:

Date today = new Date(); // Fri Jun 17 14:54:28 PDT 2016
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); // 6
int dayOfMonth = cal.get(Calendar.DAY_OF_MONTH); // 17
int dayOfYear = cal.get(Calendar.DAY_OF_YEAR); //169

int month = cal.get(Calendar.MONTH); // 5
int year = cal.get(Calendar.YEAR); // 2016

You can see that this method return an int value which is not very meaningful except the Year part. Thankfully, Calendar corrected one mistake of java.util.Date class which returns date from 1900 but rest of them is still similar to java.util.Date and difficult to read. The DayOfWeek is 6, which means FRIDAY because it starts with SUNDAY being 1.

DayOfMonth is fine as it denotes 17th, which is good. The day of the year also looks good but look at the Month, most of the people think 5 means May because that's the 5th Month but it means June here because the first month in Calendar starts with 0, which is January. This issue is sorted in Java 8 by using Enum to represent DayOfWeek and Month as an enumeration type. See Java SE 8 for Really Impatient to learn more about new Date and Time API of Java 8.

How to get the current day, month, year from Date in Java 8



Getting Month, Year and Day of Date in Java 8

So, we know how to get these value in Java 6 and Java 7, now it's time to look at how to get month and year from the date in Java 8. As I said, you can use LocalDate to represent a date in Java 8. It's a pure date value without any time element in it e.g. "14-12-2016" or "20161214". The LocalDate class also provides several getter methods to extract these values as shown below:

LocalDate currentDate = LocalDate.now(); // 2016-06-17
DayOfWeek dow = currentDate.getDayOfWeek(); // FRIDAY
int dom = currentDate.getDayOfMonth(); // 17
int doy = currentDate.getDayOfYear(); // 169
Month m = currentDate.getMonth(); // JUNE
int y = currentDate.getYear(); // 2016

You can see all values now make sense and the API is also clear and easy to use. You don't need to use any other class like Calendar to extract individual fields from Date in Java 8. This is a great advantage in terms of readability, maintainability, and ease of debugging.  You can further read Java 8 in Action to learn more about using the LocalDate class in Java 8.

How to get the current day, month, year from LocalDate in Java 8


Java Program to get day, month, year from Date in Java 8

Here is our sample Java program to obtain current day, month, and the year from a Date in Java. In this example, I have shown you how to achieve this in both Java 8 and previous versions e.g. JDK 7 or JDK 6. In Java 8, I have used new Date and Time API which means date refer here to LocalDateLocalDateTime, or ZonedDateTime, while in previous version date refers to java.util.Date object.

How to get the current day, month, year from LocalDate in Java 8 example



Java Program to obtain day, month and year from Date and LocalDate
package test;

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.Month;
import java.util.Calendar;
import java.util.Date;

/**
 * Java Program to get current day, month, year, and dayOfweek in both Java 8
 * and before e.g. JDK 1.6 and JDK 1.7
 */
public class Test {

  public static void main(String[] args) {

    // Before Java 8
    Date today = new Date();
    Calendar cal = Calendar.getInstance();
    cal.setTime(today); // don't forget this if date is arbitrary
    int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK); // 1 being Sunday
    int dayOfMonth = cal.get(Calendar.DAY_OF_MONTH);
    int dayOfYear = cal.get(Calendar.DAY_OF_YEAR);

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

    System.out.println("current date : " + today);
    System.out.println("dayOfWeek from date in Java 6 : " + dayOfWeek);
    System.out.println("dayOfMonth from a date in Java 7 : " + dayOfMonth);
    System.out.println("dayOfYear from a date in Java 1.6 : " + dayOfYear);
    System.out.println("month from a date in Java 1.7 : " + month);
    System.out.println("year from date in JDK 6 : " + year);

    // In Java 8
    LocalDate currentDate = LocalDate.now();
    DayOfWeek dow = currentDate.getDayOfWeek();
    int dom = currentDate.getDayOfMonth();
    int doy = currentDate.getDayOfYear();
    Month m = currentDate.getMonth();
    int y = currentDate.getYear();

    System.out.println("current local date : " + currentDate);
    System.out.println("dayOfWeek from a date in Java 8 : " + dow);
    System.out.println("dayOfMonth from date in JDK 8: " + dom);
    System.out.println("dayOfYear from a date in Java SE 8 : " + doy);
    System.out.println("month from a date in Java 1.8 : " + m);
    System.out.println("year from date in JDK 1.8 : " + y);
  }

}

Output
current date : Fri Jun 17 14:54:28 SGT 2016
dayOfWeek from date in Java 6 : 6
dayOfMonth from a date in Java 7 : 17
dayOfYear from a date in Java 1.6 : 169
month from a date in Java 1.7 : 5
year from date in JDK 6 : 2016
current local date : 2016-06-17
dayOfWeek from a date in Java 8 : FRIDAY
dayOfMonth from date in JDK 8: 17
dayOfYear from a date in Java SE 8 : 169
month from a date in Java 1.8 : JUNE
year from date in JDK 1.8 : 2016

You can see how easy it is to extract the individual date fields e.g. current day, month, year, day of the week, day of the month, day of the year in Java 8. You should always use new Java 8 classes for new code while try to refactor old code if there is budget and time.

That's all about how to get the day, month, and a year from a Date in Java. We'have learned how to do this common task in both Java 8 and earlier version e.g. Java 6 or 7. You can see it's much easier when you use the new Date and Time API in Java 8. But, if you have to then make sure you Calendar class and don't forget to set the Date by calling setTime() method, without that Calendar will be having the current date.

No comments:

Post a Comment