Date and Time in java

less than 1 minute read

Date + SimpleDateFormat

Date now = new Date();
SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");

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


// Date formatting
SimpleDateFormat fmttime = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
System.out.println(fmttime.format(new Date()));

LocalDate + DateTimeFormatter

  // Date formatting
  DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS");

  // Date parsing
  System.out.println(LocalDateTime.parse("2020-03-09T15:22:43.505", formatter));

  // Timezone
  LocalDateTime currentDateTime =;
  ZonedDateTime utcDateTime ="UTC"));
  ZonedDateTime seoulDateTime ="Asia/Seoul"));

LocalDateTime targetDateTime = LocalDateTime.of(int year, int month, int dayOfMonth, int hour, int minute, int second, int nanoOfSecond);

Elapsed time

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

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

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;




Leave a comment