Standard libraries
libs1DateTimeApi
- Path
- pkg13libs/libs1DateTimeApi.java
- Package
- pkg13libs
- Study order
- 1
- Run
- Single-file source launch
- Command
- java pkg13libs/libs1DateTimeApi.java
- Lesson
- Back to the chapter
There is no in-browser runner. This is the file from the curriculum, unchanged.
1package pkg13libs;2 3import java.time.Duration;4import java.time.LocalDate;5import java.time.LocalDateTime;6import java.time.Period;7import java.time.ZoneId;8import java.time.ZonedDateTime;9import java.time.format.DateTimeFormatter;10import java.time.temporal.ChronoUnit;11 12/*13 * libs1DateTimeApi.java14 * ---------------------15 * The modern Date/Time API (java.time, Java 8+) — immutable and thread-safe.16 *17 * DEFINITION:18 * java.time models dates, times, instants, durations, and zones with clear,19 * immutable types. It replaces the error-prone java.util.Date/Calendar.20 *21 * KEY POINTS:22 * - LocalDate/LocalTime/LocalDateTime: no time zone. ZonedDateTime: with zone.23 * - Instant: a point on the UTC timeline (good for timestamps).24 * - Period = date-based amount (years/months/days); Duration = time-based.25 * - All types are immutable: plusDays() returns a NEW object.26 */27public class libs1DateTimeApi {28 29 public static void main(String[] args) {30 LocalDate today = LocalDate.now();31 System.out.println("Today : " + today);32 System.out.println("In 30 days : " + today.plusDays(30));33 System.out.println("Day of week : " + today.getDayOfWeek());34 35 LocalDateTime now = LocalDateTime.now();36 System.out.println("\nNow : " + now);37 System.out.println("Formatted : " +38 now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));39 40 // Time zones41 ZonedDateTime tokyo = now.atZone(ZoneId.systemDefault())42 .withZoneSameInstant(ZoneId.of("Asia/Tokyo"));43 System.out.println("\nSame instant in Tokyo: " + tokyo);44 45 // Period (date span) vs Duration (time span)46 LocalDate launch = LocalDate.of(1995, 5, 23); // Java's public debut47 Period age = Period.between(launch, today);48 System.out.printf("%nJava is %d years, %d months, %d days old%n",49 age.getYears(), age.getMonths(), age.getDays());50 System.out.println("That is " + ChronoUnit.DAYS.between(launch, today) + " days");51 52 Duration meeting = Duration.ofHours(1).plusMinutes(30);53 System.out.println("\nDuration : " + meeting + " = " + meeting.toMinutes() + " minutes");54 55 // Parsing56 LocalDate parsed = LocalDate.parse("2030-12-25");57 System.out.println("\nParsed date : " + parsed + " (a " + parsed.getDayOfWeek() + ")");58 }59}