Preparing for Java Interview?

My books Grokking the Java Interview and Grokking the Spring Boot Interview can help

Download a Free Sample PDF

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

In this article, I'll show you how to get the current day, month, year, and dayOfWeek in Java 8 and earlier version like 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 the 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 like 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 a 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 attributes like 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 like month and year. Btw, if you don't know about the Calendar class in Java, I suggest you first go through a comprehensive Java course like The Complete Java MasterClass on Udemy instead of learning in bits and pieces. Once you have the fundamental understanding under your belt these things will make more sense to you.

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 a 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 the 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 the 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 returns an int value which is not very meaningful except for the Year part. Thankfully, Calendar corrected one mistake of java.util.Date class returns date from 1900 but the rest of them are 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 people think 5 means May because that's the 5th Month but it means June here because the first month in the 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. You can further see Java 8 New Features in the Simple Way course on Udemy to learn more about the 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 values 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 like "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 the Action book to learn more about using the LocalDate class in Java 8. It's one of the best books and the new version of this one is called Modern Java in Action which also contains changes made in Java 9 and 10 and must-read for a Java programmer.

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





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

Here is our sample Java program to obtain the current day, month, and year from a Date in Java. In this example, I have shown you how to achieve this in both Java 8 and previous versions like JDK 7 or JDK 6.  In Java 8, I have used the new Date and Time API which means date refers here to LocalDateLocalDateTime, or ZonedDateTime, while in the 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, the day of the week, the day of the month, the day of the year in Java 8. You should always use new Java 8 classes for new code while trying to refactor old code if there are budget and time.

That's all about how to get the day, month, and year from a Date in Java. We'have learned how to do this common task in both Java 8 and earlier version like 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.


Other Java 8 Date Time Tutorials you may like
  • How to parse String to LocalDateTime in Java 8? (tutorial)
  • How to calculate the difference between two dates in Java? (example)
  • 5 books to learn Java 8 and Functional Programming (books)
  • How to convert String to LocalDateTime in Java 8? (tutorial)
  • How to change the date format of String in Java 8? (tutorial)
  • How to compare two Dates in Java 8? (example)
  • How to convert Timestamp to Date in Java? (example)
  • How to convert java.util.Date to java.time.LocalDateTime in Java 8? (tutorial)
  • 20 Examples to learn new Date and Time API in Java 8 (example)
  • 5 Free Courses to learn Java 8 and 9 (courses)
  • How to convert old Date to new LocalDate in Java 8? (example)
  • 10 Examples to format and parse Date in Java 8? (tutorial)
  • 10 Java Date, Time, and Calendar based Questions from Interviews (questions)

Thanks for reading this article so far. If you liked this article then please share it with your friends and colleagues. If you have any questions or feedback then please drop a note.

P. S.: If you just want to learn more about new features in Java 8 then please see these Java 8 to Java 13 courses. It explains all the important features of Java 8 like lambda expressions, streams, functional interfaces, Optional, new Date Time API, and other miscellaneous changes.

4 comments:

  1. There is one tricky thing in Java. Months are numbered starting from 0. So if you want to get a current month, so it will return 0 for Jan or 11 for December, which is potential source of errors

    ReplyDelete
  2. Month m = currentDate.getMonth();
    can we store this in an int or convert this to an int like to the corresponding number
    eg january=1
    february=2

    ReplyDelete
    Replies
    1. I think Month is an enum, which already store int for storing value, if you stick with Month then you will get protection against invalid values like a month with values greater than 12 like Month m= 13, I suggest to keep using Month but technically you can use int as well.k

      Delete

Feel free to comment, ask questions if you have any doubt.