Java - Date and Time

Updated: 2019-01-24

java.time

Java 8 introduced a new package java.time for better handling date and time. It is essentially an improved version of joda-time(so joda-time is deprecated after 8)

DateTimeFormatter formatter = new DateTimeFormatterBuilder()
                                    .parseCaseInsensitive()
                                    .appendPattern("ddMMMyyyy")
                                    .toFormatter();
LocalDate date = LocalDate.parse("02APR2015", formatter);

Assert.assertEquals(date.getMonth(), Month.APRIL);

Date Conversions

Step 0: Import

import java.text.SimpleDateFormat;
import java.util.Date;

Step 1. Define format

SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");

Step 2. Conversions

//String -> Date
Date d = sdf.parse("2011/12/04 00:00:00");

//Date -> String
String dateTimeString1 = sdf.format(new Date());
String dateTimeString2 = sdf.format(System.currentTimeMillis()));
//Long -> Date
Date d = new Date(System.currentTimeMillis());

//Date -> Long
long time = d.getTime();

Running Time

record running time:

long startTime = System.currentTimeMillis();
//do something
long endTime = System.currentTimeMillis();
System.out.println((endTime - startTime)/1000);
final long start = System.nanoTime();
final long end = System.nanoTime();
System.out.println("Time (seconds) taken " + (end - start)/1.0e9);