or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

calendar-system.mdcurrent-time.mddate-time-classes.mdduration-arithmetic.mdindex.mdinstant-zoned-datetime.mdintl-formatting.md

instant-zoned-datetime.mddocs/

0

# Instant and Zoned Date-Time

1

2

Classes for representing exact moments in time and timezone-aware date-times. These classes provide precise time handling with full timezone support and epoch-based calculations.

3

4

## Capabilities

5

6

### Instant

7

8

Represents a single moment in time measured from the Unix epoch. Ideal for timestamps, logging, and any application requiring precise time measurements.

9

10

```typescript { .api }

11

/**

12

* Represents a single moment in time (Unix timestamp)

13

*/

14

class Instant {

15

/** Creates an Instant from various inputs */

16

static from(item: InstantLike | string): Instant;

17

/** Creates an Instant from epoch milliseconds */

18

static fromEpochMilliseconds(epochMilliseconds: number): Instant;

19

/** Creates an Instant from epoch nanoseconds */

20

static fromEpochNanoseconds(epochNanoseconds: bigint): Instant;

21

/** Compares two instants and returns -1, 0, or 1 */

22

static compare(one: InstantLike, two: InstantLike): ComparisonResult;

23

24

// Epoch time properties

25

readonly epochMilliseconds: number;

26

readonly epochNanoseconds: bigint;

27

28

// Time manipulation methods

29

/** Returns a new Instant with the duration added */

30

add(duration: DurationLike): Instant;

31

/** Returns a new Instant with the duration subtracted */

32

subtract(duration: DurationLike): Instant;

33

34

// Comparison and difference methods

35

/** Returns the duration from this instant until the other instant */

36

until(other: InstantLike, options?: DifferenceOptions<TimeUnit>): Duration;

37

/** Returns the duration from the other instant since this instant */

38

since(other: InstantLike, options?: DifferenceOptions<TimeUnit>): Duration;

39

/** Rounds this instant to the specified unit or precision */

40

round(roundTo: TimeUnit | RoundingOptions<TimeUnit>): Instant;

41

/** Tests if this instant equals another instant */

42

equals(other: InstantLike): boolean;

43

44

// Conversion methods

45

/** Converts this instant to a ZonedDateTime in the specified timezone */

46

toZonedDateTimeISO(timeZone: TimeZoneLike): ZonedDateTime;

47

48

// String representation methods

49

/** Returns a locale-formatted string representation */

50

toLocaleString(locales?: string | string[], options?: Intl.DateTimeFormatOptions): string;

51

/** Returns an ISO 8601 string representation */

52

toString(options?: InstantToStringOptions): string;

53

/** Returns a JSON representation (same as toString) */

54

toJSON(): string;

55

/** Throws a TypeError when used in comparison operators */

56

valueOf(): never;

57

}

58

```

59

60

**Usage Examples:**

61

62

```typescript

63

import { Temporal } from "temporal-polyfill";

64

65

// Creating instants

66

const now = Temporal.Now.instant();

67

const fromEpoch = Temporal.Instant.fromEpochMilliseconds(1640995200000);

68

const fromString = Temporal.Instant.from("2022-01-01T00:00:00Z");

69

70

// Converting from Date

71

const legacyDate = new Date();

72

const instant = legacyDate.toTemporalInstant();

73

74

// Time calculations

75

const oneHourLater = now.add({ hours: 1 });

76

const tenMinutesAgo = now.subtract({ minutes: 10 });

77

78

// Measuring time differences

79

const startTime = Temporal.Now.instant();

80

// ... do some work ...

81

const endTime = Temporal.Now.instant();

82

const elapsed = startTime.until(endTime, { smallestUnit: 'millisecond' });

83

84

// Rounding for precision

85

const roundedToSecond = now.round('second');

86

const roundedToMinute = now.round({ smallestUnit: 'minute', roundingMode: 'floor' });

87

88

// Timezone conversions

89

const inUtc = now.toZonedDateTimeISO('UTC');

90

const inNewYork = now.toZonedDateTimeISO('America/New_York');

91

const inTokyo = now.toZonedDateTimeISO('Asia/Tokyo');

92

93

// Comparisons

94

const isLater = Temporal.Instant.compare(oneHourLater, now) > 0;

95

const timeDiff = now.until(oneHourLater).total('minutes'); // 60

96

```

97

98

### ZonedDateTime

99

100

Represents a date and time with timezone information. Combines all PlainDateTime functionality with timezone handling, DST awareness, and offset calculations.

101

102

```typescript { .api }

103

/**

104

* Represents a date and time with timezone information

105

*/

106

class ZonedDateTime {

107

/** Creates a ZonedDateTime from various inputs */

108

static from(item: ZonedDateTimeLike | string, options?: ZonedDateTimeAssignmentOptions): ZonedDateTime;

109

/** Compares two zoned date-times and returns -1, 0, or 1 */

110

static compare(one: ZonedDateTimeLike, two: ZonedDateTimeLike): ComparisonResult;

111

112

// All PlainDateTime properties

113

readonly calendarId: string;

114

readonly year: number;

115

readonly month: number;

116

readonly monthCode: string;

117

readonly day: number;

118

readonly hour: number;

119

readonly minute: number;

120

readonly second: number;

121

readonly millisecond: number;

122

readonly microsecond: number;

123

readonly nanosecond: number;

124

readonly era: string | undefined;

125

readonly eraYear: number | undefined;

126

readonly dayOfWeek: number;

127

readonly dayOfYear: number;

128

readonly weekOfYear: number;

129

readonly yearOfWeek: number;

130

readonly daysInWeek: number;

131

readonly daysInMonth: number;

132

readonly daysInYear: number;

133

readonly monthsInYear: number;

134

readonly inLeapYear: boolean;

135

136

// Timezone-specific properties

137

readonly timeZoneId: string;

138

readonly offset: string;

139

readonly offsetNanoseconds: number;

140

readonly epochMilliseconds: number;

141

readonly epochNanoseconds: bigint;

142

143

// Timezone-aware computed properties

144

readonly hoursInDay: number;

145

readonly startOfDay: ZonedDateTime;

146

147

// DateTime manipulation methods (timezone-aware)

148

/** Returns a new ZonedDateTime with the duration added */

149

add(duration: DurationLike, options?: ArithmeticOptions): ZonedDateTime;

150

/** Returns a new ZonedDateTime with the duration subtracted */

151

subtract(duration: DurationLike, options?: ArithmeticOptions): ZonedDateTime;

152

/** Returns a new ZonedDateTime with the specified fields changed */

153

with(zonedDateTimeLike: ZonedDateTimeLike, options?: ZonedDateTimeAssignmentOptions): ZonedDateTime;

154

/** Changes the calendar system of this zoned date-time */

155

withCalendar(calendar: CalendarLike): ZonedDateTime;

156

/** Changes the timezone of this zoned date-time */

157

withTimeZone(timeZone: TimeZoneLike): ZonedDateTime;

158

/** Changes the time portion of this zoned date-time */

159

withPlainTime(plainTime?: PlainTimeLike): ZonedDateTime;

160

161

// Comparison and difference methods

162

/** Returns the duration from this zoned date-time until the other zoned date-time */

163

until(other: ZonedDateTimeLike, options?: DifferenceOptions<DateTimeUnit>): Duration;

164

/** Returns the duration from the other zoned date-time since this zoned date-time */

165

since(other: ZonedDateTimeLike, options?: DifferenceOptions<DateTimeUnit>): Duration;

166

/** Rounds this zoned date-time to the specified unit or precision */

167

round(roundTo: DateTimeUnit | RoundingOptions<DateTimeUnit>): ZonedDateTime;

168

/** Tests if this zoned date-time equals another zoned date-time */

169

equals(other: ZonedDateTimeLike): boolean;

170

171

// Conversion methods

172

/** Converts this zoned date-time to an Instant */

173

toInstant(): Instant;

174

/** Converts this zoned date-time to a PlainDateTime (loses timezone) */

175

toPlainDateTime(): PlainDateTime;

176

/** Extracts the date portion */

177

toPlainDate(): PlainDate;

178

/** Extracts the time portion */

179

toPlainTime(): PlainTime;

180

/** Extracts the year-month portion */

181

toPlainYearMonth(): PlainYearMonth;

182

/** Extracts the month-day portion */

183

toPlainMonthDay(): PlainMonthDay;

184

/** Gets the TimeZone object for this zoned date-time */

185

getTimeZone(): TimeZone;

186

187

// String representation methods

188

/** Returns a locale-formatted string representation */

189

toLocaleString(locales?: string | string[], options?: Intl.DateTimeFormatOptions): string;

190

/** Returns an ISO 8601 string representation with timezone */

191

toString(options?: ZonedDateTimeToStringOptions): string;

192

/** Returns a JSON representation (same as toString) */

193

toJSON(): string;

194

/** Throws a TypeError when used in comparison operators */

195

valueOf(): never;

196

}

197

```

198

199

**Usage Examples:**

200

201

```typescript

202

import { Temporal } from "temporal-polyfill";

203

204

// Creating zoned date-times

205

const nowInNewYork = Temporal.Now.zonedDateTimeISO('America/New_York');

206

const fromString = Temporal.ZonedDateTime.from('2024-03-15T14:30:00-04:00[America/New_York]');

207

const fromObject = Temporal.ZonedDateTime.from({

208

year: 2024,

209

month: 3,

210

day: 15,

211

hour: 14,

212

minute: 30,

213

timeZone: 'America/New_York'

214

});

215

216

// From PlainDateTime

217

const plainDT = Temporal.PlainDateTime.from('2024-03-15T14:30:00');

218

const zonedDT = plainDT.toZonedDateTime('America/New_York');

219

220

// Timezone conversions

221

const inLondon = nowInNewYork.withTimeZone('Europe/London');

222

const inTokyo = nowInNewYork.withTimeZone('Asia/Tokyo');

223

224

// DST-aware arithmetic

225

const springForward = Temporal.ZonedDateTime.from('2024-03-10T01:30:00-05:00[America/New_York]');

226

const afterDST = springForward.add({ hours: 2 }); // Handles DST transition

227

console.log(springForward.hoursInDay); // 23 hours (spring forward day)

228

229

// Working with business hours

230

const businessDay = Temporal.ZonedDateTime.from('2024-03-15T09:00:00[America/New_York]');

231

const endOfDay = businessDay.with({ hour: 17, minute: 0 });

232

const workingHours = businessDay.until(endOfDay, { largestUnit: 'hour' });

233

234

// Handling ambiguous times (DST transitions)

235

const ambiguousTime = Temporal.ZonedDateTime.from(

236

'2024-11-03T01:30:00[America/New_York]',

237

{ disambiguation: 'earlier' } // Choose first occurrence

238

);

239

240

// Time zone offset information

241

console.log(nowInNewYork.offset); // e.g., "-05:00" or "-04:00"

242

console.log(nowInNewYork.offsetNanoseconds); // Offset in nanoseconds

243

244

// Start of day in timezone (handles DST)

245

const startOfDay = nowInNewYork.startOfDay;

246

const midnight = nowInNewYork.with({ hour: 0, minute: 0, second: 0 });

247

248

// Conversions

249

const instant = nowInNewYork.toInstant();

250

const plainDateTime = nowInNewYork.toPlainDateTime();

251

const justDate = nowInNewYork.toPlainDate();

252

253

// Comparisons across timezones

254

const nyTime = Temporal.ZonedDateTime.from('2024-01-01T12:00:00[America/New_York]');

255

const londonTime = Temporal.ZonedDateTime.from('2024-01-01T17:00:00[Europe/London]');

256

const areEqual = nyTime.equals(londonTime); // true - same instant

257

```

258

259

### Global Date Extension

260

261

Extension to the native Date object for converting to Temporal types.

262

263

```typescript { .api }

264

/**

265

* Extension to Date.prototype for Temporal integration

266

*/

267

interface Date {

268

/** Converts a legacy Date to a Temporal.Instant */

269

toTemporalInstant(): Instant;

270

}

271

```

272

273

**Usage Examples:**

274

275

```typescript

276

// Converting legacy dates

277

const legacyDate = new Date();

278

const instant = legacyDate.toTemporalInstant();

279

const zonedDateTime = instant.toZonedDateTimeISO(Temporal.Now.timeZoneId());

280

281

// Migration pattern

282

function modernizeTimestamp(legacyTimestamp: Date): Temporal.ZonedDateTime {

283

return legacyTimestamp

284

.toTemporalInstant()

285

.toZonedDateTimeISO('UTC');

286

}

287

```

288

289

## Types

290

291

```typescript { .api }

292

// Core type definitions for instants and zoned date-times

293

type InstantLike = Instant | string;

294

type ZonedDateTimeLike = ZonedDateTime | ZonedDateTimeFields | string;

295

type TimeZoneLike = string | TimeZone;

296

297

interface ZonedDateTimeFields {

298

era?: string;

299

eraYear?: number;

300

year: number;

301

month?: number;

302

monthCode?: string;

303

day: number;

304

hour?: number;

305

minute?: number;

306

second?: number;

307

millisecond?: number;

308

microsecond?: number;

309

nanosecond?: number;

310

timeZone: TimeZoneLike;

311

offset?: string;

312

calendar?: CalendarLike;

313

}

314

315

// Timezone-specific options

316

type DisambiguationMode = 'compatible' | 'earlier' | 'later' | 'reject';

317

type OffsetDisambiguationMode = 'use' | 'ignore' | 'prefer' | 'reject';

318

319

interface ZonedDateTimeAssignmentOptions extends AssignmentOptions {

320

disambiguation?: DisambiguationMode;

321

offset?: OffsetDisambiguationMode;

322

}

323

324

// String formatting options

325

interface InstantToStringOptions {

326

timeZone?: TimeZoneLike;

327

fractionalSecondDigits?: 'auto' | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9;

328

smallestUnit?: TimeUnit;

329

roundingMode?: RoundingMode;

330

}

331

332

interface ZonedDateTimeToStringOptions {

333

fractionalSecondDigits?: 'auto' | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9;

334

smallestUnit?: DateTimeUnit;

335

roundingMode?: RoundingMode;

336

timeZoneName?: 'auto' | 'never' | 'critical';

337

offset?: 'auto' | 'never';

338

calendarName?: 'auto' | 'always' | 'never' | 'critical';

339

}

340

341

// TimeZone interface (for reference)

342

interface TimeZone {

343

readonly id: string;

344

getOffsetNanosecondsFor(instant: Instant): number;

345

getOffsetStringFor(instant: Instant): string;

346

getPlainDateTimeFor(instant: Instant, calendar?: CalendarLike): PlainDateTime;

347

getInstantFor(dateTime: PlainDateTime, options?: ToInstantOptions): Instant;

348

getPossibleInstantsFor(dateTime: PlainDateTime): Instant[];

349

getNextTransition(startingPoint: Instant): Instant | null;

350

getPreviousTransition(startingPoint: Instant): Instant | null;

351

toString(): string;

352

toJSON(): string;

353

}

354

355

interface ToInstantOptions {

356

disambiguation?: DisambiguationMode;

357

}

358

```