Java Date cookbook

By Maurizio Farina | Posted on September 2017

How to get current date time?

The java class is : java.util.Date

1
new Date();

How to format the current date time?

1
2
3
4
5
6
//define format and timezone to use
SimpleDateFormat  dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));

//Convert Date to String using date format
System.out.println(dateFormat.format(new Date())); 

How to parse string Date?

1
2
3
4
5
6
7
//define format and timezone to use
SimpleDateFormat  dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));

//Parse the String daye using date format
Date date = dateFormat.parse("2017/05/17 23:00");
System.out.println(dateFormat.format(date)); 

Convert Date to java.sql.Date

1
2
3
4
5
6
7
SimpleDateFormat  dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
df.setTimeZone(TimeZone.getTimeZone("UTC"));

//Parse the String daye using date format
Date date = df.parse("2017/05/17 23:00");

new java.sql.Date(date.getTime());

Calculate difference between Two Date

The java.util.Date instance is not a date but an instant. The instance stores milliseconds since the Unix Epoch time. Unix Epoch Time uses midnight at the start of January 1st 1970 in UTC - Coordinated Universal Time.

So, the differnce between java.util.Date is just to calculate difference between two instants (Long number):

1
2
long diffInMillies = Math.abs(end.getTime() - start.getTime());
duration = TimeUnit.SECONDS.convert(diffInMillies, TimeUnit.MILLISECONDS);