Guide to java.util.Date Class
Learn to create new date, get current date, parse date to string or format Date object using java.util.Date class. These usecases are frequently required, and having them in one place will help in saving time for many of us.
It is worth noting that there is no timezone information associated with Date instance. A Date instance represents the time spent since Epach in milliseconds. If we print the date instance, it always prints the default or local timezone of the machine. So the timezone information printed in Date.toString() method should not misguide you.
1. Formatting a Date to String
Java program of formatting Date to string using SimpleDateFormat.format() . Please note that SimpleDateFormat is not a thread-safe class, so we should not share its instance with multiple threads.
SimpleDateFormat sdf = new SimpleDateFormat("dd/M/yyyy"); String date = sdf.format(new Date());
Refer SimpleDateFormat JavaDoc for detailed date and time patterns. Below is a list of the most common pattern letters you can use.
y = year (yy or yyyy) M = month (MM) d = day in month (dd) h = hour (0-12) (hh) H = hour (0-23) (HH) m = minute in hour (mm) s = seconds (ss) S = milliseconds (SSS) z = time zone text (e.g. Pacific Standard Time. ) Z = time zone, time offset (e.g. -0800)
Pattern | Example |
---|---|
yyyy-MM-dd (ISO) | “2018-07-14” |
dd-MMM-yyyy | “14-Jul-2018” |
dd/MM/yyyy | “14/07/2018” |
E, MMM dd yyyy | “Sat, Jul 14 2018” |
h:mm a | “12:08 PM” |
EEEE, MMM dd, yyyy HH:mm:ss a | “Saturday, Jul 14, 2018 14:31:06 PM” |
yyyy-MM-dd’T’HH:mm:ssZ | “2018-07-14T14:31:30+0530” |
hh ‘o»clock’ a, zzzz | “12 o’clock PM, Pacific Daylight Time” |
K:mm a, z | “0:08 PM, PDT” |
2. Parsing a String to Date
Java program of parsing a string to Date instance using SimpleDateFormat.parse() method.
SimpleDateFormat sdf = new SimpleDateFormat("dd-M-yyyy hh:mm:ss"); String dateInString = "15-10-2015 10:20:56"; Date date = sdf.parse(dateInString);
3. Getting Current Date and Time
java.util.Date class represents the date and time elapsed since the epoch. Given below are the Java programs for getting the current date and time and printing in a given format.
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); Date date = new Date(); System.out.println(dateFormat.format(date));
For reference, since Java 8, we can use LocalDate , LocalTime and LocalDateTime classes.
LocalDate today = LocalDate.now(); System.out.println("Today's Local date : " + today); LocalTime time = LocalTime.now(); System.out.println("local time now : " + time);
4. Convert between Date and Calendar
4.1. Converting Calendar to Date
Calendar calendar = Calendar.getInstance(); Date date = calendar.getTime();
4.2. Converting Date to Calendar
SimpleDateFormat sdf = new SimpleDateFormat("dd-M-yyyy hh:mm:ss"); String dateInString = "27-04-2016 10:22:56"; Date date = sdf.parse(dateInString); Calendar calendar = Calendar.getInstance(); calendar.setTime(date);
We can compare two two date instances using its compareTo() method. It returns an integer value representing given date is before or after another date.
The comparison date1.CompareTo(date2) will return:
- a value 0 if date2 is equal to date1;
- a value less than 0 if date1 is before date2;
- a value greater than 0 if date1 is after date2.
Date date1 = new Date(); Date date2 = new Date(); int comparison = date1.compareTo(date2);
6. Extracting Days, Months and Years
Java program to get date parts such as year, month, etc separately.
The methods to get the year, month, day of the month, hour, etc. are deprecated. If you need to get or set the year, month, day of the month, etc. use a java.util.Calendar instead.
Calendar calendar = Calendar.getInstance(); calendar.setTime(new Date()); int year = calendar.get(Calendar.YEAR); int month = calendar.get(Calendar.MONTH); int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH); // Jan = 0, not 1 int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK); int weekOfYear = calendar.get(Calendar.WEEK_OF_YEAR); int weekOfMonth= calendar.get(Calendar.WEEK_OF_MONTH); int hour = calendar.get(Calendar.HOUR); // 12 hour clock int hourOfDay = calendar.get(Calendar.HOUR_OF_DAY); // 24 hour clock int minute = calendar.get(Calendar.MINUTE); int second = calendar.get(Calendar.SECOND); int millisecond= calendar.get(Calendar.MILLISECOND);
Get Year, Month and Day from Date in Java
Learn to get the year, month and day from a given date in Java using the new LocalDate class as well as legacy java.util.Date class.
1. Get Day, Month and Year since Java 8
The new Date Time API, added in Java 8, has several classes capable of storing a date (day, month and year). A few of them are:
The above classes provide the methods to query the day, month and year information from a given instance.
- getYear() – returns the year as int value.
- getMonthValue() – returns the month as a number from 1 to 12.
- getDayOfMonth() – returns the int value for the day-of-month.
Java program to extract the day, month and year from a date in Java 8.
LocalDate today = LocalDate.now(); //23-Feb-022 int day = today.getDayOfMonth(); //23 int month = today.getMonthValue(); //2 int year = today.getYear(); //2022
We can invoke these same methods with LocalDateTime and other classes as well. Except for LocalDate, other classes provide methods to extract hours, minutes and seconds.
2. Get Day, Month and Year from java.util.Date
Directly pulling the day, month and year information from a java.util.Date instance is NOT possible. We must convert the Date to Calendar instance.
The Calendar class provides the following constants that we can use to query the date parts.
- Calendar.DAY_OF_MONTH – field indicating the day of the month.
- Calendar.MONTH – field indicating the month from 0 to 11.
- Calendar.YEAR – field indicating the year.
Java program to extract the day, month and year from a Date using Calendar.
Date date = new Date(); //23-Feb-022 Calendar calendar = Calendar.getInstance(); calendar.setTime(date); int day = calendar.get(Calendar.DAY_OF_MONTH); //23 int month = calendar.get(Calendar.MONTH); //1 int year = calendar.get(Calendar.YEAR); //2022
In this Java tutorial, we learned to extract the integer values for the day, month and year information from new date API classes and the old legacy Java classes.
It is highly recommended to use the new Date API as it provides many specialized classes and methods for all kinds of usecases.