Date and Time in java

less than 1 minute read

Date + SimpleDateFormat

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

// 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");
  System.out.println(LocalDateTime.now().format(formatter));

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

  // Timezone
  LocalDateTime currentDateTime = LocalDateTime.now();
  ZonedDateTime utcDateTime = ZonedDateTime.now(ZoneId.of("UTC"));
  ZonedDateTime seoulDateTime = ZonedDateTime.now(ZoneId.of("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 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