Java - Date and Time

Updated: 2019-05-11

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)

jshell> import java.time.LocalDate;

jshell> LocalDate date = LocalDate.parse("2020-01-01");
date ==> 2020-01-01

jshell> date.getYear()
$3 ==> 2020

Timezone

jshell> import java.time.ZoneId;

jshell> ZoneId zoneId = ZoneId.of("America/Los_Angeles");
zoneId ==> America/Los_Angeles

Start of day

jshell> date.atStartOfDay(zoneId);
$6 ==> 2020-01-01T00:00-08:00[America/Los_Angeles]

jshell> date.atStartOfDay(zoneId).toEpochSecond();
$7 ==> 1577865600

End of day. There's no .atEndOfDay() method though.

jshell> date.plusDays(1).atStartOfDay(zoneId);
$8 ==> 2020-01-02T00:00-08:00[America/Los_Angeles]
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);