Date and Time API
Uses the java.time API to work with dates, times, durations, periods, and formatting, demonstrating modern date-time manipulation and parsing.
Code
import java.time.*;
import java.time.format.*;
import java.time.temporal.*;
public class DateTimeHandling {
public static void main(String[] args) {
LocalDate today = LocalDate.now();
LocalTime now = LocalTime.now();
LocalDateTime dateTime = LocalDateTime.now();
ZonedDateTime zoned = ZonedDateTime.now(ZoneId.of("America/New_York"));
System.out.println("Today: " + today);
System.out.println("Now: " + now);
System.out.println("NY Time: " + zoned);
LocalDate birthday = LocalDate.of(1990, 5, 15);
Period age = Period.between(birthday, today);
System.out.println("Age: " + age.getYears() + " years");
Duration duration = Duration.between(
LocalTime.of(9, 0),
LocalTime.of(17, 30)
);
System.out.println("Work hours: " + duration.toHours() + "h " +
(duration.toMinutesPart()) + "m");
String formatted = dateTime.format(
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
);
System.out.println("Formatted: " + formatted);
LocalDate parsed = LocalDate.parse("2025-01-15");
System.out.println("Parsed: " + parsed.getDayOfWeek());
LocalDate nextWeek = today.plus(1, ChronoUnit.WEEKS);
System.out.println("Next week: " + nextWeek);
}
}How the snippet works
All of the logic lives in the class DateTimeHandling and the function main.
Using it
The primary signature is public static void main(String[] args)
The run emits 8 labeled sections — Today:, Now:, NY Time:, Age:, Work hours:, Formatted:, Parsed:, Next week: — one per step.
Key statements
ZonedDateTime zoned = ZonedDateTime.now(ZoneId.of("America/New_York"));
LocalDate nextWeek = today.plus(1, ChronoUnit.WEEKS);
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
);
Interactive Tools for This Topic
Duration HumanizerTurn a number of seconds into a readable duration such as 1 day, 2 hours, 3 minutes, and show the equivalent in minutes and hours.Date Add/Subtract CalculatorAdd or subtract days, weeks, months, or years from a date, clamping month ends such as January 31 plus one month.Date Difference CalculatorCalculate the number of days, weeks, whole months, and years between two ISO dates, computed in UTC.Duration ConverterConvert between human durations like 1w2d3h45m and total seconds, hours, and minutes with negative support.
FAQ
- What does Date and Time API print when run?
- Run it as a complete program — the output lines carry labels such as `Today:`, `Now:`, `NY Time:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.