Part VI: Working with Dates and Date formatting in Java

By | March 14, 2021

Introduction to the Date class in Java

When building programs in any programming language, there might come a time when it would be useful to be able to log a date and a time for a certain event, action or other. In Java we can use the Date class to create a Date instance object, which can then be formatted using either the DateFormat class in Java or the SimpleDateFormat class.

I personally usually go with the SimpleDateFormat class since I find it easier to use and has suited most of my needs when it comes to Date formatting. It also helps that it uses a really simple syntax for specifying which format you wish to format your Date to.

You might wonder why we need so many classes if there already is a Date class in Java, well the return types of month, year, date, hour, minute, second are all in a very “raw” format as follows:

  • A year is represented as an integer value y – 1900
  • A month is represented by an integer value as well, where 0 is January and 11 is December.
  • A date (day of month) is represented also as an integer value, this one however, starting from 1 all the way to 31
  • An hour is represented by an integer value starting at 0 that can reach all the way to 23
  • A minute is represented by an integer value starting at 0 as well, going to 59
  • A second is represented by an integer value going from 0 to 61 (61 because of leap seconds, you can read more about those here if interested)

The Date class itself represent a specific instant in time using millisecond precision
– Paraphrased from the Date class Java oracle documentation page

The Date class may no longer be able to format Dates itself (lots of deprecated methods that didn’t hold up to international standards – hence the Formatting classes to go with the Date class), but it still contains some very useful methods to work with the Date class and its instance objects. See table below:

Method Return
.after(Date obj) Returns boolean (Tests if the Date object the method is called on, is after the input parameter Date obj)
.before(Date obj) Returns boolean (Same as above method, but instead checks if the Date object the method is called on comes before the input parameter Date obj)
.compareTo(Date obj) Returns an integer – 0 if input parameter Date object are equal to the Date object the method is called on, less than 0 if the Date object the method is called on comes before the input parameter Date object, greater than 0 if the Date object the method is called on comes after the input parameter Date object
.equals(Date obj) Returns boolean true/false whether both the Date objects are equal to the millisecond (based on using .getTime() methods returned long value)
.getTime() Returns long value of the number of milliseconds since January 1, 1970 00:00:00 GMT of the Date object the method is called on
.setTime(long time) Void method that sets the time value of the Date object to the time in milliseconds since January 1, 1970 00:00:00 GMT (Have fun calculating that one :P)
.toString() Converts the Date object .toString() is called on to a String with the following pre-programmed format: dow mon dd hh:mm:ss zzz yyyy
Where dow = day of the week (sun, mon, tue, wed, thu, fri, sat)
mon = Month represented in 3 letter String value
dd = Day of the month 01-31 (2x d’s to get 2 decimal values no matter what day of month)
hh = Hour of the day 00-23 (2x h’s to get 2 decimal values for the hour no matter which hour)
mm = Minute of the hour 00-59 (2x m’s to get 2 decimal values for minute regardless of which minute)
ss = Second of the minute 00-61 (2x s’s to get 2 decimal values for the second here as well)
zzz = Time zone
yyyy = Year represented with 4 decimal values, hence 4x y’s :)So the .toString() method would then return something like: Sun Mar 14 17:05:23 GMT+1 2021 for me for when I’m sitting here writing this article right now.

So you see there are ways of working solely with the Date class, but that would require us to do a lot of heavy lifting to format dates the way we want them to be formatted, that is why we will be using external classes/libraries for this functionality. To save us both time and effort.

A fun exercise if you feel like experimenting a bit, could be to create a new Date object, call on the .getTime() method, store the return value as a long variable, and try from there to calculate what year it is, what month of the year, what day, what hour of the day, what minute of the hour and what second of the minute. For this remember when it starts counting the milliseconds to determine the date (Jan 1, 1970 00:00:00 GMT). If you decide to try it out, I wish you best of luck ;)!

How to create a Date object in Java

Creating a Date object is no harder than this in Java:

Date date = new Date();

Simple as that, once you create a Date object it will be of the date and time for when your program called the constructor to create the object of the Date class. Since that is when it calls upon the System.currentTimeMillis(); method.

Could be useful to remember for later when working with Date objects :)

Using System to get current time in milliseconds

Fun fact – as mentioned above, the Java Date class uses the Java System class in it’s constructor to fetch the current time in milliseconds from the System you’re on, using the method System.currentTimeMillis();

So if you want to build your very own Date class as a fun exercise, you could also use this method and create your own formatting methods, Getters and Setters :)

Introduction to the DateFormat class in Java

DateFormat can be used to format the Date object to various Locales and timezones. I won’t go into more detail about the DateFormat class because my goal with this article was to cover its subclass SimpleDateFormat for formatting the Date objects as Strings for how you want them to be presented in your program :)

One methods caught my eye when browsing through the Oracle Java documentation for the DateFormat class however, the .getTimeZone(); method. These could be great if you ever want to (or need to) find out the timezone of your date. See example below:

DateFormat df = DateFormat.getDateInstance();

The .getTimeZone(); method doesn’t print a very user friendly result, but that may be because it returns a TimeZone object of the TimeZone class. Also something not intended to cover in this article, but feel free to browse through its Oracle Java documentation if interested.

Other than that, if you want to read more about DateFormat class in Java, check out the Oracle Java documentation.

Introduction to SimpleDateFormat in Java

Now, to finally what was intended to be covered in this article – The SimpleDateFormat class, which also turns out to be a subclass of the DateFormat class itself in Java, and is specialized for formatting date->text and text->date.

We will be showing you various syntaxes and explaining them, so that you can use them freely and with full control to create your preferred date formatting that you wish to have in your program.

The SimpleDateFormat class allows you to specify whichever Date formatting pattern you wish to craft your representation of the date with by using the class syntax and it will make your wishes come true.

How to use SimpleDateFormat class in Java to format dates

For us to do an effective coverage of how to use the SimpleDateFormat class in Java, we need to paraphrase/borrow the table of the formatting syntax from the Oracle Java documentation so that you can see what symbol represents what and then we can discuss how we can use it in practice, as well as how we can manipulate and craft our pattern Strings for how we want our Dates to be represented in our program. Alright, so lets get started, check out the formatting table reference below:

Symbol Representation Example
y Year 1996; 96
M Month in year March; Mar; 03
w Week in year 27
W Week in month 2
D Day in year 189
d Day in month 15
E Day name in week Monday; Mon
u Day number of week (Monday = 1) 1
H Hour in day (0-23) 22
m Minute in hour 45
s Second in minute 59
z General Time Zone GMT +1:00

Note: Above table have most of the options available for formatting of Dates with SimpleDateFormat, but it’s a limited selection I made based on my personal experience for what usually ends up being most common for brevity’s sake. But for the full reference and more in-depth information for SimpleDateFormat class and how to work with it, check out the Oracle Java documentation.

You can use the symbol 2-4+ times to represent the date component the way you want – for example: 4x y’s gives you 1996, 2x y’s give you 96.

If you assign more than 4, the pattern will show full representation of the datetime component, no matter how long.

The pattern I keep mentioning is basically formatted as a regular String value, so for example: "yyyy-MM-dd".

I will demonstrate a few practical examples of formatting styles you can use, also please experiment freely on your own to find the combo you desire to format your Dates with. I will also demonstrate how you in practice apply this designed formatting style pattern to a Date object. See examples below:

Date date = new Date(); 
Date time = new Date(); // Notice that the "time" might be a few milliseconds off (maybe) compared to the first date object, because of program execution time and system performance

SimpleDateFormat currentDate = new SimpleDateFormat("yyyy-MM-dd"); // Notice the regular String character that is NOT part of formatting option, that can then be used to separate/style the combo of formatting options, in this case "-"
SimpleDateFormat currentTime = new SimpleDateFormat("hh:mm:ss"); // Notice the regular String character ":" I can use to separate the various datetime formatting options

System.out.println(currentDate.format(date)); // This will print: 2021-03-14    - Do however note that .format(Date obj) method returns StringBuffer technically, but it can still be stored as a String variable 
System.out.println(currentTime.format(time)); // This will print: 08:48:15

See how simple it was to create a Date object that stores the current time from the system in milliseconds, and then you simply format it using the syntax available in SimpleDateFormat to get the representation you want :) Easy peasy – and very useful – whether it’s for virtual banking programs, log file printouts, or something else. A very useful feature in Java programming to learn.

Leave a Reply

Your email address will not be published. Required fields are marked *