Master Java Date/Time: From Legacy Date to Modern LocalDateTime
This guide covers Java date/time handling from legacy Date and SimpleDateFormat to modern JDK 8+ APIs including LocalDateTime, DateTimeFormatter, Period, and Duration with practical code examples and conversion techniques.
Traditional Date and SimpleDateFormat
The legacy java.util.Date class represents a specific instant in time with millisecond precision since the Unix epoch (January 1, 1970 00:00:00 UTC). In China (UTC+8), the epoch appears as 1970-01-01 08:00:00.
import java.util.Date;
public class DateDemo {
public static void main(String[] args) {
// No-arg constructor returns current system time
Date date1 = new Date();
System.out.println(date1);
// Constructor with milliseconds since epoch
Date date2 = new Date(0L);
// Prints Thu Jan 01 08:00:00 CST 1970
System.out.println(date2);
Date date3 = new Date();
// Get milliseconds since epoch
long time1 = date3.getTime();
System.out.println(time1);
// Static shortcut for current milliseconds
long time2 = System.currentTimeMillis();
System.out.println(time2);
Date date4 = new Date();
// Set time via milliseconds since epoch
date4.setTime(0L);
System.out.println(date4); // epoch time
}
}SimpleDateFormatformats Date objects into custom strings and parses strings back into Date objects. Pattern letters: yyyy year, MM month, dd day, HH hour (0-23), mm minute, ss second.
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateDemo {
public static void main(String[] args) {
Date date1 = new Date();
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
String result = sdf1.format(date1);
System.out.println(result);
String str = "2012-12-12 12:12:12";
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");
Date date2 = null;
try {
date2 = sdf2.parse(str);
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println(date2);
}
}JDK 8+ Modern Date/Time API
The java.time package introduces immutable, thread-safe classes:
LocalDate — date only (year-month-day)
LocalTime — time only (hour-minute-second)
LocalDateTime — date and time combined
DateTimeFormatter — formatting and parsing
Period — date-based intervals (years, months, days)
Duration — time-based intervals (seconds, milliseconds, nanoseconds)
LocalDateTime Core Usage
import java.time.LocalDateTime;
public class LocalDateTimeDemo {
public static void main(String[] args) {
// Current system date-time
LocalDateTime now = LocalDateTime.now();
System.out.println(now);
// Specific date-time via of()
LocalDateTime localDateTime = LocalDateTime.of(2022, 12, 12, 11, 11, 11);
System.out.println(localDateTime);
}
}Common Getter Methods
getYear()— year (e.g., 2022) getMonthValue() — month 1-12 getDayOfMonth() — day of month 1-31 getDayOfYear() — day of year 1-366 getDayOfWeek() — DayOfWeek enum getHour() — hour 0-23 getMinute() — minute 0-59 getSecond() — second 0-59
Formatting and Parsing with DateTimeFormatter
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class LocalDateTimeDemo {
public static void main(String[] args) {
// String to LocalDateTime
String str1 = "2022-11-11 12:13:15";
DateTimeFormatter pattern1 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime parse = LocalDateTime.parse(str1, pattern1);
System.out.println(parse);
// LocalDateTime to String
LocalDateTime localDateTime = LocalDateTime.of(2022, 12, 12, 23, 59, 59);
System.out.println(localDateTime);
DateTimeFormatter pattern2 = DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH时mm分ss秒");
String str2 = localDateTime.format(pattern2);
System.out.println(str2);
}
}Date Arithmetic: plus* Methods
All plus* methods accept positive values to add and negative values to subtract. Each returns a new LocalDateTime instance. plusYears(long years) — add/subtract years plusMonths(long months) — add/subtract months plusDays(long days) — add/subtract days plusHours(long hours) — add/subtract hours plusMinutes(long minutes) — add/subtract minutes plusSeconds(long seconds) — add/subtract seconds plusWeeks(long weeks) — add/subtract weeks
Field Modification: with* Methods
Each with* method returns a new instance with the specified field replaced. withYear(int year) — set year withMonth(int month) — set month withDayOfMonth(int dayOfMonth) — set day of month withDayOfYear(int dayOfYear) — set day of year withHour(int hour) — set hour withMinute(int minute) — set minute withSecond(int second) — set second
Period: Date-Based Intervals
Period.between(start, end)computes the difference between two LocalDate objects. Getter methods return component-wise differences (not totals).
import java.time.LocalDate;
import java.time.Period;
public class PeriodDemo {
public static void main(String[] args) {
LocalDate localDate1 = LocalDate.of(2022, 1, 1);
LocalDate localDate2 = LocalDate.of(2050, 12, 12);
Period period = Period.between(localDate1, localDate2);
System.out.println(period); // P28Y11M11D
System.out.println(period.getYears()); // 28
System.out.println(period.getMonths()); // 11
System.out.println(period.getDays()); // 11
System.out.println(period.toTotalMonths()); // 347
/*
* getYears()/getMonths()/getDays() return component differences:
* year diff, month diff, day diff — NOT totals.
* toTotalMonths() returns the total months across the whole period.
* No toTotalDays() or toTotalYears() exists.
*/
}
}Duration: Time-Based Intervals
Duration.between(start, end)works with LocalDateTime (or Instant). All to* methods return total amounts in the target unit.
import java.time.Duration;
import java.time.LocalDateTime;
public class DurationDemo {
public static void main(String[] args) {
LocalDateTime localDateTime1 = LocalDateTime.of(2021, 1, 1, 12, 12, 12);
LocalDateTime localDateTime2 = LocalDateTime.of(2022, 2, 1, 12, 12, 12);
Duration duration = Duration.between(localDateTime1, localDateTime2);
System.out.println(duration); // PT9504H
System.out.println(duration.toDays()); // 396
System.out.println(duration.toHours()); // 9504
System.out.println(duration.toMinutes()); // 570240
System.out.println(duration.toSeconds()); // 34214400
System.out.println(duration.toMillis()); // 34214400000
System.out.println(duration.toNanos()); // 34214400000000000
/*
* All to*() methods return total quantities in that unit,
* which are the values commonly needed in practice.
*/
}
}Interoperability: Date ↔ LocalDateTime
Date to LocalDateTime
import java.util.Date;
import java.time.ZoneId;
import java.time.LocalDateTime;
public class Test {
public static void main(String[] args) {
// Way 1: via Instant and system default zone
Date d1 = new Date();
LocalDateTime ldt1 = d1.toInstant()
.atZone(ZoneId.systemDefault())
.toLocalDateTime();
System.out.println(d1);
System.out.println(ldt1);
System.out.println("----------------");
// Way 2: LocalDateTime.ofInstant
Date d2 = new Date();
LocalDateTime ldt2 = LocalDateTime.ofInstant(d2.toInstant(), ZoneId.systemDefault());
System.out.println(d2);
System.out.println(ldt2);
}
}LocalDateTime to Date
import java.time.ZonedDateTime;
import java.util.Date;
import java.time.ZoneId;
import java.time.LocalDateTime;
public class Test {
public static void main(String[] args) {
LocalDateTime ldt = LocalDateTime.now();
ZonedDateTime zdt = ldt.atZone(ZoneId.systemDefault());
Date dd = Date.from(zdt.toInstant());
System.out.println(ldt);
System.out.println(dd);
}
}Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
