Skip to content

Latest commit

 

History

History
75 lines (57 loc) · 2.14 KB

File metadata and controls

75 lines (57 loc) · 2.14 KB
title Work with Dates and Times using DateTime
id data-datetime
skillLevel intermediate
applicationPatternId core-concepts
summary Use DateTime for immutable, time-zone-aware date and time values, enabling safe and precise time calculations.
tags
DateTime
date
time
timezone
data-type
effect
rule
description
Use DateTime to represent and manipulate dates and times in a type-safe, immutable, and time-zone-aware way.
related
representing-time-spans-with-duration
data-struct
author PaulJPhilp
lessonOrder 22

Work with Dates and Times using DateTime

Guideline

Use the DateTime data type to represent and manipulate dates and times in a type-safe, immutable, and time-zone-aware way.
This enables safe, precise, and reliable time calculations in your applications.

Rationale

JavaScript's native Date is mutable, not time-zone-aware, and can be error-prone.
DateTime provides an immutable, functional alternative with explicit time zone handling and robust APIs for time arithmetic.

Good Example

import { DateTime } from "effect";

// Create a DateTime for the current instant (returns an Effect)
import { Effect } from "effect";

const program = Effect.gen(function* () {
  const now = yield* DateTime.now; // DateTime.Utc

  // Parse from ISO string
  const parsed = DateTime.unsafeMakeZoned("2024-07-19T12:34:56Z"); // DateTime.Zoned

  // Add or subtract durations
  const inOneHour = DateTime.add(now, { hours: 1 });
  const oneHourAgo = DateTime.subtract(now, { hours: 1 });

  // Format as ISO string
  const iso = DateTime.formatIso(now); // e.g., "2024-07-19T23:33:19.000Z"

  // Compare DateTimes
  const isBefore = DateTime.lessThan(oneHourAgo, now); // true

  return { now, inOneHour, oneHourAgo, iso, isBefore };
});

Explanation:

  • DateTime is immutable and time-zone-aware.
  • Supports parsing, formatting, arithmetic, and comparison.
  • Use for all date/time logic to avoid bugs with native Date.

Anti-Pattern

Using JavaScript's mutable Date for time calculations, or ignoring time zones, which can lead to subtle and hard-to-debug errors.