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)
PatternExample
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);

5. Comparing Two Dates

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);

Happy Learning !!

Comments

Subscribe
Notify of
guest
3 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode