Date and Time in java
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 seoulDateTime = ZonedDateTime.now(ZoneId.of("Asia/Seoul"));
ZonedDateTime utcDateTime = ZonedDateTime.now(ZoneId.of("UTC"));
ZonedDateTime newYorkDateTime = ZonedDateTime.now(ZoneId.of("America/New_York"));
System.out.println("Current : " + currentDateTime.toLocalDate() + " " + currentDateTime.toLocalTime());
System.out.println("Seoul : " + seoulDateTime.toLocalDate() + " " + seoulDateTime.toLocalTime());
System.out.println("UTC : " + utcDateTime.toLocalDate() + " " + utcDateTime.toLocalTime());
System.out.println("NewYork : " + newYorkDateTime.toLocalDate() + " " + newYorkDateTime.toLocalTime());
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