Java - Date and Time

Updated: 2018-06-17

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);