Java Date and Time API

Modern date and time handling using java.time package (LocalDate, LocalTime, LocalDateTime, ZonedDateTime)

java (8+) 2025-11-03 datetime java8 time date

Description

Java 8 introduced the new Date and Time API in the java.time package, providing a comprehensive and immutable date-time API. It replaces the problematic java.util.Date and Calendar classes.

Key Classes

  • LocalDate: Date without time (year-month-day)
  • LocalTime: Time without date (hour-minute-second)
  • LocalDateTime: Date and time without timezone
  • ZonedDateTime: Date and time with timezone
  • Instant: Point in time (Unix timestamp)
  • Duration: Time-based amount (hours, minutes, seconds)
  • Period: Date-based amount (years, months, days)

Common Operations

  • Create dates and times
  • Format and parse dates
  • Calculate differences
  • Add/subtract time periods
  • Convert between timezones

Code

RAW
import java.time.*;import java.time.format.*;import java.time.temporal.*;public class DateTimeUtils {        // Get current date    public static LocalDate getCurrentDate() {        return LocalDate.now();    }        // Get current time    public static LocalTime getCurrentTime() {        return LocalTime.now();    }        // Get current date-time    public static LocalDateTime getCurrentDateTime() {        return LocalDateTime.now();    }        // Create date    public static LocalDate createDate(int year, int month, int day) {        return LocalDate.of(year, month, day);    }        // Create time    public static LocalTime createTime(int hour, int minute) {        return LocalTime.of(hour, minute);    }        // Parse date from string    public static LocalDate parseDate(String dateStr) {        return LocalDate.parse(dateStr);    }        // Format date to string    public static String formatDate(LocalDate date, String pattern) {        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);        return date.format(formatter);    }        // Add days    public static LocalDate addDays(LocalDate date, long days) {        return date.plusDays(days);    }        // Calculate difference in days    public static long daysBetween(LocalDate date1, LocalDate date2) {        return ChronoUnit.DAYS.between(date1, date2);    }        // Get start of day    public static LocalDateTime startOfDay(LocalDate date) {        return date.atStartOfDay();    }        // Convert to Instant    public static Instant toInstant(LocalDateTime dateTime, ZoneId zoneId) {        return dateTime.atZone(zoneId).toInstant();    }        // Get duration between times    public static Duration durationBetween(LocalTime time1, LocalTime time2) {        return Duration.between(time1, time2);    }}
RAW
// Current date and timeLocalDate today = LocalDate.now();LocalTime now = LocalTime.now();LocalDateTime current = LocalDateTime.now();// Create specific dateLocalDate date = LocalDate.of(2024, 1, 15);LocalTime time = LocalTime.of(14, 30);LocalDateTime dateTime = LocalDateTime.of(2024, 1, 15, 14, 30);// Parse from stringLocalDate parsed = LocalDate.parse("2024-01-15");LocalDateTime parsedDateTime = LocalDateTime.parse("2024-01-15T14:30:00");// Format to stringDateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");String formatted = dateTime.format(formatter);// Add/subtract timeLocalDate tomorrow = today.plusDays(1);LocalDate nextWeek = today.plusWeeks(1);LocalDate nextMonth = today.plusMonths(1);LocalDate nextYear = today.plusYears(1);LocalTime later = now.plusHours(2);LocalTime earlier = now.minusMinutes(30);// Calculate differencelong days = ChronoUnit.DAYS.between(today, tomorrow);Duration duration = Duration.between(now, later);Period period = Period.between(today, tomorrow);// Compare datesboolean isAfter = tomorrow.isAfter(today);boolean isBefore = today.isBefore(tomorrow);boolean isEqual = today.equals(today);// Get specific fieldsint year = today.getYear();Month month = today.getMonth();int day = today.getDayOfMonth();DayOfWeek dayOfWeek = today.getDayOfWeek();// With timezoneZonedDateTime zoned = ZonedDateTime.now(ZoneId.of("America/New_York"));Instant instant = zoned.toInstant();// Convert between zonesZonedDateTime utc = zoned.withZoneSameInstant(ZoneId.of("UTC"));

Comments

No comments yet. Be the first to comment!