Date and Time in java

less than 1 minute read

Date and time format

Date now = new Date();
SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
System.out.println(format.format(now)); 

Date today = new Date();
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSS");
String cdate = format.format(today);

System.currentTimeMillis()

Elapsed time

You can use currentTimeMillis() to estimate elapsed time and show them with formatting.

long startTime = System.currentTimeMillis();
// ... do something ...
long estimatedTime = System.currentTimeMillis() - startTime;

You may prefer to use System.nanoTime() if you are looking for extremely precise measurements of elapsed time.

long startTime = System.nanoTime();    
// ... the code being measured ...    
long estimatedTime = System.nanoTime() - startTime;

Tags:

Categories:

Updated:

Leave a comment