Java Code Examples: DateTime

java.util.Date is in core java API since Java 1.0. And it is not recommended for use. If you are using Java 8 or a later version, it is better to use java.time.LocalDate and java.time.Instant, which were introduced in Java 8.

In this post, I will cover common operations related to datetime.

Get current datetime

Instant

Instant now = Instant.now(); // Capture the current moment in UTC, with a resolution of nanoseconds. Returns a `Instant` object.
ZoneId zoneId = ZoneId.of("Asia/Shanghai");
ZonedDateTime zdt = instant.atZone(zoneId);

ZonedDateTime

ZonedDateTime zonedDateTime = ZonedDateTime.now();

LocalDateTime

LocalDateTime localDateTime = LocalDateTime.now();

java.util.Date

Date date = new Date();

Format and parse datetime

Instant

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
.withZone(ZoneId.systemDefault());
Instant now = Instant.now();
System.out.println(formatter.format(now));
Instant fromString = Instant.parse("2024-12-01T17:30:01Z");
System.out.println(fromString);

ZonedDateTime

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
.withZone(ZoneId.systemDefault());
ZonedDateTime now = ZonedDateTime.now();
System.out.println(formatter.format(now));
ZonedDateTime fromString = ZonedDateTime.parse("2024-12-01 17:30:01", formatter);
System.out.println(fromString);

LocalDateTime

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime now = LocalDateTime.now();
// conver to formatted string
System.out.println(now.format(formatter));
// convert from string
LocalDateTime fromDateTimeString = LocalDateTime.parse("2024-12-01 17:30:01", formatter);
System.out.println(fromDateTimeString);

java.util.Date

DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date now = new Date();
// convert to formatted string
System.out.println(formatter.format(now));
// convert from string
Date date = formatter.parse("2024-12-01 17:30:01");
System.out.println(date);

Extract information from a datetime

LocalDate

LocalDate localDate = LocalDate.now();  
int year = localDate.getYear();
System.out.println(year);
// month start from 1.
int monthValue = localDate.getMonthValue();
System.out.println(monthValue);
int dayOfMonth = localDate.getDayOfMonth();
System.out.println(dayOfMonth);

java.util.Date

Date date = new Date();  
Calendar calendar = Calendar.getInstance(); calendar.setTime(date);

int year = calendar.get(Calendar.YEAR);
System.out.println(year);
// month start from 0. January is 0.
int month = calendar.get(Calendar.MONTH);
System.out.println(month);
int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);
System.out.println(dayOfMonth);

DateTime Type in Java