FrontendDeveloper.in

ECMAScript question detail

Temporal API

The Temporal API is a new date and time API for JavaScript that addresses many of the limitations of the existing Date object. It provides a modern, immutable, and more intuitive way to work with dates and times.

// Get the current date
const today = Temporal.Now.plainDate();
console.log(today.toString()); // e.g., "2025-06-01"

// Create a specific date
const date = Temporal.PlainDate.from("2025-06-01");
console.log("Year:", date.year);      // 2025
console.log("Month:", date.month);    // 6
console.log("Day:", date.day);        // 1
console.log("Day of week:", date.dayOfWeek); // e.g., 7 (Sunday)

// Date arithmetic
const futureDate = date.add({ months: 1, days: 15 });
console.log(futureDate.toString()); // "2025-07-16"

// Calculate duration between dates
const duration = date.until(futureDate);
console.log(duration.toString()); // "P1M15D" (1 month, 15 days)

The Temporal API includes several objects for different date/time representations:

  1. Temporal.Now: Provides methods to get the current date and time in various formats.
  2. Temporal.Instant: Represents a fixed point in time (like a timestamp).
  3. Temporal.PlainDate: Represents a calendar date without time or timezone.
  4. Temporal.PlainTime: Represents wall-clock time without date or timezone.
  5. Temporal.PlainDateTime: Combines date and time without timezone.
  6. Temporal.ZonedDateTime: Full date, time, and timezone information.
  7. Temporal.Duration: Represents a length of time.
  8. Temporal.TimeZone: Represents a timezone.
  9. Temporal.Calendar: Represents a calendar system.

The Temporal API is particularly useful for applications that need to handle dates and times across different timezones:

// Calculate flight duration between timezones
function calculateFlightDuration(departure, arrival) {
const departureTZ = Temporal.ZonedDateTime.from(departure);
const arrivalTZ = Temporal.ZonedDateTime.from(arrival);
return departureTZ.until(arrivalTZ);
}

const flightDeparture = "2025-06-01T08:30:00-04:00[America/New_York]";
const flightArrival = "2025-06-01T22:15:00+02:00[Europe/Paris]";
console.log("Flight duration:", calculateFlightDuration(flightDeparture, flightArrival).toString());
// e.g., "PT9H45M" (9 hours, 45 minutes)
Back to all ECMAScript questions
Get LinkedIn Premium at Rs 399