Date and Time in Java

 

Date and time are among the most frequently used features of every programming language. For example, most of the time we like logging exact date and time when an object was created, or deleted, or when a specific method was called. Java language has a built-in class to support date and time, java.util.Date. Date class may keep the date and time information along with time zone. In addition, Java provides java.util.Calendar class to process date and time.

A Date object can be constructed using one of the two constructors.

Date() – no-arg constructor, creates a date object with the current date and timezone of the operating system on which JVM runs

Date(long) – takes number of milliseconds since 01/01/1970 in Greenwich time as an argument and turns that into a Date object. By default, JVM sets the timezone of the Date object to the timezone of the operating system on which the JVM runs.

toString() method of the Date class can be invoked on the Date object to get information.

Let’s see this in an example.

public class MyClass {

public static void main(String [] args) {

Date date = new Date(0);

System.out.println(date);

date = new Date();

System.out.println(date);

}

}

The output would depend on the operating system and time the program is run. On a computer with Pacific Standard Time, on 01/01/2016 at midnight, the output would look as follows:

Wed Dec 31 16:00:00 PST 1969

Fri Jan 01 00:00:00 PST 2016

The reason for the first line of the output not being January 1st, 1970 is that, there’s a 8 hours difference between Greenwich time and PST.

Java Calendar

java.util.Calendar class is a utility class for processing dates. It can be used to create new instances of Date with year, month, day of month, hour, minute, second, millisecond input. In addition, it provides utility methods for operations like getting day of the week, etc. Calendar class’ getTime() method returns a java.util.Date object, with all the information processed in the Calendar object.

One thing we need to keep in mind regarding Calendar object is that calendar month starts from 0, corresponding to January. For Calendar days, Sunday is the first day of the week, with index 1. Days of the month also starts from 1, not from 0.

A new instance of Calendar object with the current time can be created using Calendar.getInstance() method.

Let’s see how the Calendar object works in an example.

public class MyClass {

public static void main(String [] args) {

Calendar calendar = Calendar.getInstance();

calendar.set(Calendar.YEAR, 2016);

calendar.set(Calendar.MONTH, 0);

calendar.set(Calendar.DAY_OF_MONTH, 1);

calendar.set(Calendar.HOUR, 0);

calendar.set(Calendar.MINUTE, 0);

calendar.set(Calendar.SECOND, 0);

Date date = calendar.getTime();

System.out.println(date);

System.out.println(calendar.get(Calendar.DAY_OF_WEEK));

}

}

The output would be

Fri Jan 01 12:00:00 PST 2016

6

As can be seen in the output, by default the new Calendar instance has the timezone of the operating system on which JVM runs, PST in this case. Starting from Sunday, Friday is the 6th day of the week and therefore, for day of the week, 6 is printed on the console.

Parsing the date from a string

A java.util.Date object can also be parsed from a String with the appropriate format, using java.util.SimpleDateFormat class. SimpleDateFormat class is a subclass of java.util.DateFormat class. While parsing a date, first a SimpleDateFormat object is initialized with a date format string using the constructor

SimpleDateFormat(String)

The date format String is a template for parsing a date from a string. It contains the information about how the date is displayed. For example, yyyy-MM-dd HH:mm:ss.SSS is the date format for a date representing String like, 2016-01-01 05:02:00.952. In this example, the date has information down to the milliseconds. The components of the date that are not contained in the date format string are by default set to 0. For example, if a date like 2016-02-01 is parsed with a date format string like yyyy-MM-dd, the resulting date is equivalent to 2016-02-01 00:00:00.000.

The signature of the parse method is as follows:

public java.util.Date parse(String) throws ParseException

In this method, the String argument is the string that will be converted into a Date.

Let’s see this in an example.

public class MyClass {

public static void main(String [] args) throws ParseException {

DateFormat df = new SimpleDateFormat(“yyyy-MM-dd”);

Date date = df.parse(“2016-01-01”);

System.out.println(date);

}

}

The output would be

Fri Jan 01 00:00:00 PST 2016

Because ParseException is a checked exception, the main() method in this example needs to honor catch or specify requirement for checked exceptions.

Formatting Dates

SimpleDateFormat class can be used to format dates, too, with a given date format string to be used as a template. The signature of the format method is as follows:

public String format(Date)

Let’s see how this works in an example.

public class MyClass {

public static void main(String [] args) throws Exception {

DateFormat df = new SimpleDateFormat(“yyyy-MM-dd”);

Date date = new Date();;

System.out.println(df.format(date));

}

}

The output would be dependent on the timezone of the operating system that JVM runs on and the current time. It would look something like

2016-01-01