or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

comparison-validation.mdcreation-parsing.mddisplay-formatting.mdduration.mdgetters-setters.mdindex.mdlocale.mdmanipulation.mdutilities.md

utilities.mddocs/

0

# Utility and Static Methods

1

2

Static utility functions for type checking, min/max operations, normalization, global configuration, and other helper functions that operate on Moment instances or provide general utilities.

3

4

## Capabilities

5

6

### Type Checking Utilities

7

8

Static methods for determining the type of values, particularly useful for type guards and validation.

9

10

```javascript { .api }

11

/**

12

* Check if a value is a Moment instance

13

* @param m - Value to check

14

* @returns true if value is a Moment instance, false otherwise

15

*/

16

function isMoment(m: any): m is Moment;

17

18

/**

19

* Check if a value is a native Date instance

20

* @param m - Value to check

21

* @returns true if value is a Date instance, false otherwise

22

*/

23

function isDate(m: any): m is Date;

24

25

/**

26

* Check if a value is a Duration instance

27

* @param d - Value to check

28

* @returns true if value is a Duration instance, false otherwise

29

*/

30

function isDuration(d: any): d is Duration;

31

```

32

33

**Usage Examples:**

34

35

```javascript

36

import moment from "moment";

37

38

const momentObj = moment();

39

const dateObj = new Date();

40

const durationObj = moment.duration(2, "hours");

41

const stringValue = "2023-12-25";

42

const numberValue = 1640447400000;

43

const plainObject = { year: 2023, month: 11, day: 25 };

44

45

// Type checking

46

console.log(moment.isMoment(momentObj)); // true

47

console.log(moment.isMoment(dateObj)); // false

48

console.log(moment.isMoment(stringValue)); // false

49

console.log(moment.isMoment(numberValue)); // false

50

51

console.log(moment.isDate(dateObj)); // true

52

console.log(moment.isDate(momentObj)); // false

53

console.log(moment.isDate(stringValue)); // false

54

55

console.log(moment.isDuration(durationObj)); // true

56

console.log(moment.isDuration(momentObj)); // false

57

console.log(moment.isDuration(numberValue)); // false

58

59

// Practical usage in functions

60

function safeMoment(input) {

61

if (moment.isMoment(input)) {

62

return input.clone(); // Already a moment, clone to avoid mutation

63

} else if (moment.isDate(input)) {

64

return moment(input); // Convert Date to Moment

65

} else {

66

return moment(input); // Parse string/number/etc

67

}

68

}

69

70

function formatAnyDate(input) {

71

const momentInstance = safeMoment(input);

72

return momentInstance.format("YYYY-MM-DD");

73

}

74

75

// Type guards in conditional logic

76

function processTimeValue(value) {

77

if (moment.isMoment(value)) {

78

return value.format("YYYY-MM-DD HH:mm:ss");

79

} else if (moment.isDate(value)) {

80

return moment(value).format("YYYY-MM-DD HH:mm:ss");

81

} else if (moment.isDuration(value)) {

82

return value.humanize();

83

} else {

84

return "Invalid time value";

85

}

86

}

87

88

// Array filtering with type checks

89

const mixedArray = [

90

moment(),

91

new Date(),

92

moment.duration(2, "hours"),

93

"2023-12-25",

94

123456789

95

];

96

97

const onlyMoments = mixedArray.filter(moment.isMoment);

98

const onlyDates = mixedArray.filter(moment.isDate);

99

const onlyDurations = mixedArray.filter(moment.isDuration);

100

101

console.log(onlyMoments.length); // 1

102

console.log(onlyDates.length); // 1

103

console.log(onlyDurations.length); // 1

104

```

105

106

### Min/Max Operations

107

108

Find the earliest or latest moment from a collection of moments.

109

110

```javascript { .api }

111

/**

112

* Find the earliest (minimum) moment from an array

113

* @param moments - Array of moments to compare

114

* @returns The earliest moment from the array

115

*/

116

function min(moments: Moment[]): Moment;

117

118

/**

119

* Find the earliest (minimum) moment from variable arguments

120

* @param moments - Variable number of moment arguments

121

* @returns The earliest moment from the arguments

122

*/

123

function min(...moments: Moment[]): Moment;

124

125

/**

126

* Find the latest (maximum) moment from an array

127

* @param moments - Array of moments to compare

128

* @returns The latest moment from the array

129

*/

130

function max(moments: Moment[]): Moment;

131

132

/**

133

* Find the latest (maximum) moment from variable arguments

134

* @param moments - Variable number of moment arguments

135

* @returns The latest moment from the arguments

136

*/

137

function max(...moments: Moment[]): Moment;

138

```

139

140

**Usage Examples:**

141

142

```javascript

143

import moment from "moment";

144

145

// Create array of moments

146

const dates = [

147

moment("2023-12-25"),

148

moment("2023-01-15"),

149

moment("2023-06-30"),

150

moment("2023-03-10"),

151

moment("2023-11-05")

152

];

153

154

// Find min and max from array

155

const earliest = moment.min(dates);

156

const latest = moment.max(dates);

157

158

console.log(earliest.format("YYYY-MM-DD")); // "2023-01-15"

159

console.log(latest.format("YYYY-MM-DD")); // "2023-12-25"

160

161

// Using variable arguments

162

const min1 = moment.min(

163

moment("2023-01-01"),

164

moment("2023-06-15"),

165

moment("2023-03-20")

166

);

167

console.log(min1.format("YYYY-MM-DD")); // "2023-01-01"

168

169

const max1 = moment.max(

170

moment("2023-01-01"),

171

moment("2023-06-15"),

172

moment("2023-03-20")

173

);

174

console.log(max1.format("YYYY-MM-DD")); // "2023-06-15"

175

176

// Practical examples

177

function getDateRange(appointments) {

178

const moments = appointments.map(apt => moment(apt.date));

179

return {

180

start: moment.min(moments),

181

end: moment.max(moments)

182

};

183

}

184

185

const appointments = [

186

{ date: "2023-12-25T10:00:00", title: "Meeting 1" },

187

{ date: "2023-12-20T14:30:00", title: "Meeting 2" },

188

{ date: "2023-12-30T09:00:00", title: "Meeting 3" }

189

];

190

191

const range = getDateRange(appointments);

192

console.log(`Appointments from ${range.start.format("MMM D")} to ${range.end.format("MMM D")}`);

193

// "Appointments from Dec 20 to Dec 30"

194

195

// Handle empty arrays safely

196

function safeMin(moments) {

197

if (moments.length === 0) {

198

return null;

199

}

200

return moment.min(moments);

201

}

202

203

function safeMax(moments) {

204

if (moments.length === 0) {

205

return null;

206

}

207

return moment.max(moments);

208

}

209

210

// Find business hours range

211

const workTimes = [

212

moment("2023-12-25T09:00:00"),

213

moment("2023-12-25T12:30:00"),

214

moment("2023-12-25T17:00:00"),

215

moment("2023-12-25T08:30:00")

216

];

217

218

const workStart = moment.min(workTimes);

219

const workEnd = moment.max(workTimes);

220

console.log(`Work day: ${workStart.format("HH:mm")} to ${workEnd.format("HH:mm")}`);

221

// "Work day: 08:30 to 17:00"

222

```

223

224

### Current Time Utility

225

226

Get the current time in milliseconds, with ability to override for testing.

227

228

```javascript { .api }

229

/**

230

* Get the current time in milliseconds since Unix epoch

231

* This function can be overridden for testing purposes

232

* @returns Current time in milliseconds

233

*/

234

function now(): number;

235

```

236

237

**Usage Examples:**

238

239

```javascript

240

import moment from "moment";

241

242

// Get current timestamp

243

const currentTime = moment.now();

244

console.log(currentTime); // e.g., 1703517045123

245

246

// Same as Date.now() and +moment()

247

console.log(moment.now() === Date.now()); // approximately true (within milliseconds)

248

console.log(moment.now() === +moment()); // approximately true

249

250

// Override for testing (useful in test environments)

251

const originalNow = moment.now;

252

moment.now = function() {

253

return moment("2023-12-25T15:30:00").valueOf();

254

};

255

256

console.log(moment().format()); // Always returns "2023-12-25T15:30:00..."

257

258

// Restore original function

259

moment.now = originalNow;

260

261

// Practical usage for timestamps

262

function logEvent(message) {

263

const timestamp = moment.now();

264

const readable = moment(timestamp).format("YYYY-MM-DD HH:mm:ss");

265

console.log(`[${readable}] ${message}`);

266

}

267

268

logEvent("User logged in"); // [2023-12-25 15:30:45] User logged in

269

270

// Performance timing

271

const startTime = moment.now();

272

// ... some operation ...

273

const endTime = moment.now();

274

const duration = moment.duration(endTime - startTime);

275

console.log(`Operation took ${duration.asMilliseconds()}ms`);

276

```

277

278

### Invalid Moment Creation

279

280

Create explicitly invalid moments for error handling and testing.

281

282

```javascript { .api }

283

/**

284

* Create an explicitly invalid Moment instance

285

* @param flags - Optional parsing flags for debugging invalid state

286

* @returns Invalid Moment instance

287

*/

288

function invalid(flags?: MomentParsingFlagsOpt): Moment;

289

290

interface MomentParsingFlagsOpt {

291

empty?: boolean;

292

unusedTokens?: string[];

293

unusedInput?: string[];

294

overflow?: number;

295

charsLeftOver?: number;

296

nullInput?: boolean;

297

invalidMonth?: string;

298

invalidFormat?: boolean;

299

userInvalidated?: boolean;

300

iso?: boolean;

301

parsedDateParts?: any[];

302

meridiem?: string;

303

}

304

```

305

306

**Usage Examples:**

307

308

```javascript

309

import moment from "moment";

310

311

// Create invalid moment

312

const invalidMoment = moment.invalid();

313

console.log(invalidMoment.isValid()); // false

314

console.log(invalidMoment.format()); // "Invalid date"

315

316

// Create invalid moment with debugging info

317

const invalidWithFlags = moment.invalid({

318

invalidFormat: true,

319

userInvalidated: true

320

});

321

322

const flags = invalidWithFlags.parsingFlags();

323

console.log(flags.invalidFormat); // true

324

console.log(flags.userInvalidated); // true

325

326

// Practical usage for error handling

327

function safeParseDateString(dateString) {

328

if (!dateString || typeof dateString !== 'string') {

329

return moment.invalid({ nullInput: true });

330

}

331

332

const parsed = moment(dateString, "YYYY-MM-DD", true); // strict parsing

333

if (!parsed.isValid()) {

334

return moment.invalid({ invalidFormat: true });

335

}

336

337

return parsed;

338

}

339

340

// Test the function

341

const validDate = safeParseDateString("2023-12-25");

342

const invalidDate = safeParseDateString("invalid-date");

343

const nullDate = safeParseDateString(null);

344

345

console.log(validDate.isValid()); // true

346

console.log(invalidDate.isValid()); // false

347

console.log(nullDate.isValid()); // false

348

349

// Handle invalid moments in processing

350

function processDate(input) {

351

const moment = safeParseDateString(input);

352

353

if (!moment.isValid()) {

354

const flags = moment.parsingFlags();

355

if (flags.nullInput) {

356

return { error: "No input provided" };

357

} else if (flags.invalidFormat) {

358

return { error: "Invalid date format" };

359

} else {

360

return { error: "Unknown parsing error" };

361

}

362

}

363

364

return { date: moment.format("YYYY-MM-DD") };

365

}

366

367

console.log(processDate("2023-12-25")); // { date: "2023-12-25" }

368

console.log(processDate("invalid")); // { error: "Invalid date format" }

369

console.log(processDate(null)); // { error: "No input provided" }

370

```

371

372

### Unit Normalization

373

374

Normalize time unit strings to canonical forms.

375

376

```javascript { .api }

377

/**

378

* Normalize a time unit string to its canonical form

379

* @param unit - Time unit string to normalize

380

* @returns Normalized unit string, or null if invalid

381

*/

382

function normalizeUnits(unit: unitOfTime.All): string;

383

```

384

385

**Usage Examples:**

386

387

```javascript

388

import moment from "moment";

389

390

// Normalize various unit strings

391

console.log(moment.normalizeUnits("year")); // "year"

392

console.log(moment.normalizeUnits("years")); // "year"

393

console.log(moment.normalizeUnits("y")); // "year"

394

console.log(moment.normalizeUnits("Y")); // "year"

395

396

console.log(moment.normalizeUnits("month")); // "month"

397

console.log(moment.normalizeUnits("months")); // "month"

398

console.log(moment.normalizeUnits("M")); // "month"

399

400

console.log(moment.normalizeUnits("day")); // "day"

401

console.log(moment.normalizeUnits("days")); // "day"

402

console.log(moment.normalizeUnits("d")); // "day"

403

404

console.log(moment.normalizeUnits("hour")); // "hour"

405

console.log(moment.normalizeUnits("hours")); // "hour"

406

console.log(moment.normalizeUnits("h")); // "hour"

407

408

console.log(moment.normalizeUnits("minute")); // "minute"

409

console.log(moment.normalizeUnits("minutes")); // "minute"

410

console.log(moment.normalizeUnits("m")); // "minute"

411

412

console.log(moment.normalizeUnits("second")); // "second"

413

console.log(moment.normalizeUnits("seconds")); // "second"

414

console.log(moment.normalizeUnits("s")); // "second"

415

416

console.log(moment.normalizeUnits("millisecond")); // "millisecond"

417

console.log(moment.normalizeUnits("milliseconds")); // "millisecond"

418

console.log(moment.normalizeUnits("ms")); // "millisecond"

419

420

// Special units

421

console.log(moment.normalizeUnits("quarter")); // "quarter"

422

console.log(moment.normalizeUnits("Q")); // "quarter"

423

console.log(moment.normalizeUnits("week")); // "week"

424

console.log(moment.normalizeUnits("w")); // "week"

425

console.log(moment.normalizeUnits("isoWeek")); // "isoWeek"

426

console.log(moment.normalizeUnits("W")); // "isoWeek"

427

428

// Invalid units return null

429

console.log(moment.normalizeUnits("invalid")); // null

430

console.log(moment.normalizeUnits("")); // null

431

432

// Practical usage

433

function createFlexibleDuration(amount, unit) {

434

const normalizedUnit = moment.normalizeUnits(unit);

435

if (!normalizedUnit) {

436

throw new Error(`Invalid time unit: ${unit}`);

437

}

438

return moment.duration(amount, normalizedUnit);

439

}

440

441

// All of these work the same way

442

const duration1 = createFlexibleDuration(2, "hour");

443

const duration2 = createFlexibleDuration(2, "hours");

444

const duration3 = createFlexibleDuration(2, "h");

445

446

console.log(duration1.asHours()); // 2

447

console.log(duration2.asHours()); // 2

448

console.log(duration3.asHours()); // 2

449

450

// Validation function

451

function isValidTimeUnit(unit) {

452

return moment.normalizeUnits(unit) !== null;

453

}

454

455

console.log(isValidTimeUnit("days")); // true

456

console.log(isValidTimeUnit("invalid")); // false

457

```

458

459

### Relative Time Configuration

460

461

Configure global settings for relative time display and thresholds.

462

463

```javascript { .api }

464

/**

465

* Get current relative time threshold for a unit

466

* @param threshold - Threshold identifier ("ss", "s", "m", "h", "d", "M")

467

* @returns Current threshold value or boolean indicating if set

468

*/

469

function relativeTimeThreshold(threshold: string): number | boolean;

470

471

/**

472

* Set relative time threshold for a unit

473

* @param threshold - Threshold identifier to set

474

* @param limit - New threshold value

475

* @returns true if threshold was set successfully

476

*/

477

function relativeTimeThreshold(threshold: string, limit: number): boolean;

478

479

/**

480

* Get current relative time rounding function

481

* @returns Current rounding function

482

*/

483

function relativeTimeRounding(): (num: number) => number;

484

485

/**

486

* Set relative time rounding function

487

* @param fn - Function to use for rounding relative time values

488

* @returns true if rounding function was set successfully

489

*/

490

function relativeTimeRounding(fn: (num: number) => number): boolean;

491

```

492

493

**Usage Examples:**

494

495

```javascript

496

import moment from "moment";

497

498

// Get current thresholds

499

console.log(moment.relativeTimeThreshold("ss")); // 44 (seconds to show "a few seconds")

500

console.log(moment.relativeTimeThreshold("s")); // 45 (seconds to show "a minute")

501

console.log(moment.relativeTimeThreshold("m")); // 45 (minutes to show "an hour")

502

console.log(moment.relativeTimeThreshold("h")); // 22 (hours to show "a day")

503

console.log(moment.relativeTimeThreshold("d")); // 26 (days to show "a month")

504

console.log(moment.relativeTimeThreshold("M")); // 11 (months to show "a year")

505

506

// Test default behavior

507

const test1 = moment().subtract(30, "seconds");

508

const test2 = moment().subtract(50, "seconds");

509

console.log(test1.fromNow()); // "a few seconds ago"

510

console.log(test2.fromNow()); // "a minute ago"

511

512

// Customize thresholds

513

moment.relativeTimeThreshold("ss", 10); // Show "a few seconds" only for <= 10 seconds

514

moment.relativeTimeThreshold("s", 60); // Show "a minute" up to 60 seconds

515

516

const test3 = moment().subtract(30, "seconds");

517

console.log(test3.fromNow()); // "30 seconds ago" (now shows specific seconds)

518

519

// Reset thresholds

520

moment.relativeTimeThreshold("ss", 44);

521

moment.relativeTimeThreshold("s", 45);

522

523

// Custom rounding function

524

const originalRounding = moment.relativeTimeRounding();

525

console.log(originalRounding(2.6)); // 3 (default rounds normally)

526

527

// Set custom rounding (always floor)

528

moment.relativeTimeRounding(Math.floor);

529

530

const testRounding = moment().subtract(2.8, "hours");

531

console.log(testRounding.fromNow()); // Uses floor rounding

532

533

// Set custom rounding (always ceiling)

534

moment.relativeTimeRounding(Math.ceil);

535

536

// Restore original rounding

537

moment.relativeTimeRounding(originalRounding);

538

539

// Practical example: more precise relative times

540

function configurePreciseRelativeTime() {

541

// Show exact seconds for first minute

542

moment.relativeTimeThreshold("ss", 0); // Never show "a few seconds"

543

moment.relativeTimeThreshold("s", 60); // Show seconds up to 60

544

545

// Show exact minutes for first hour

546

moment.relativeTimeThreshold("m", 60); // Show minutes up to 60

547

548

// Show exact hours for first day

549

moment.relativeTimeThreshold("h", 24); // Show hours up to 24

550

}

551

552

configurePreciseRelativeTime();

553

554

const now = moment();

555

console.log(now.clone().subtract(30, "seconds").fromNow()); // "30 seconds ago"

556

console.log(now.clone().subtract(45, "minutes").fromNow()); // "45 minutes ago"

557

console.log(now.clone().subtract(12, "hours").fromNow()); // "12 hours ago"

558

```

559

560

### Calendar Format Utility

561

562

Get the calendar format string for displaying relationships between moments.

563

564

```javascript { .api }

565

/**

566

* Get the calendar format string for the relationship between two moments

567

* @param m - The moment to format

568

* @param now - Reference moment (usually current time)

569

* @returns Calendar format key ("sameDay", "nextDay", etc.)

570

*/

571

function calendarFormat(m: Moment, now: Moment): string;

572

```

573

574

**Usage Examples:**

575

576

```javascript

577

import moment from "moment";

578

579

const now = moment("2023-12-25T15:30:00");

580

const today = moment("2023-12-25T10:00:00");

581

const tomorrow = moment("2023-12-26T10:00:00");

582

const yesterday = moment("2023-12-24T10:00:00");

583

const nextWeek = moment("2024-01-01T10:00:00");

584

const lastWeek = moment("2023-12-18T10:00:00");

585

const farFuture = moment("2024-06-15T10:00:00");

586

587

// Get calendar format keys

588

console.log(moment.calendarFormat(today, now)); // "sameDay"

589

console.log(moment.calendarFormat(tomorrow, now)); // "nextDay"

590

console.log(moment.calendarFormat(yesterday, now)); // "lastDay"

591

console.log(moment.calendarFormat(nextWeek, now)); // "nextWeek"

592

console.log(moment.calendarFormat(lastWeek, now)); // "lastWeek"

593

console.log(moment.calendarFormat(farFuture, now)); // "sameElse"

594

595

// Use with locale data to get format strings

596

const localeData = moment.localeData();

597

const formats = {

598

sameDay: localeData._config.calendar.sameDay,

599

nextDay: localeData._config.calendar.nextDay,

600

lastDay: localeData._config.calendar.lastDay,

601

nextWeek: localeData._config.calendar.nextWeek,

602

lastWeek: localeData._config.calendar.lastWeek,

603

sameElse: localeData._config.calendar.sameElse

604

};

605

606

console.log(formats);

607

// {

608

// sameDay: '[Today at] LT',

609

// nextDay: '[Tomorrow at] LT',

610

// lastDay: '[Yesterday at] LT',

611

// nextWeek: 'dddd [at] LT',

612

// lastWeek: '[Last] dddd [at] LT',

613

// sameElse: 'L'

614

// }

615

616

// Practical usage for custom calendar formatting

617

function customCalendarFormat(targetMoment, referenceMoment = moment()) {

618

const formatKey = moment.calendarFormat(targetMoment, referenceMoment);

619

const localeData = moment.localeData();

620

621

switch (formatKey) {

622

case "sameDay":

623

return targetMoment.format("[Today at] HH:mm");

624

case "nextDay":

625

return targetMoment.format("[Tomorrow at] HH:mm");

626

case "lastDay":

627

return targetMoment.format("[Yesterday at] HH:mm");

628

case "nextWeek":

629

return targetMoment.format("dddd [at] HH:mm");

630

case "lastWeek":

631

return targetMoment.format("[Last] dddd [at] HH:mm");

632

default:

633

return targetMoment.format("YYYY-MM-DD HH:mm");

634

}

635

}

636

637

console.log(customCalendarFormat(today, now)); // "Today at 10:00"

638

console.log(customCalendarFormat(tomorrow, now)); // "Tomorrow at 10:00"

639

console.log(customCalendarFormat(farFuture, now)); // "2024-06-15 10:00"

640

```

641

642

### Two-Digit Year Parsing

643

644

Utility for parsing two-digit years with century logic.

645

646

```javascript { .api }

647

/**

648

* Parse a two-digit year string into a four-digit year

649

* Years 00-68 are interpreted as 2000-2068

650

* Years 69-99 are interpreted as 1969-1999

651

* @param input - Two-digit year string

652

* @returns Four-digit year as number

653

*/

654

function parseTwoDigitYear(input: string): number;

655

```

656

657

**Usage Examples:**

658

659

```javascript

660

import moment from "moment";

661

662

// Parse two-digit years

663

console.log(moment.parseTwoDigitYear("00")); // 2000

664

console.log(moment.parseTwoDigitYear("01")); // 2001

665

console.log(moment.parseTwoDigitYear("23")); // 2023

666

console.log(moment.parseTwoDigitYear("68")); // 2068

667

console.log(moment.parseTwoDigitYear("69")); // 1969

668

console.log(moment.parseTwoDigitYear("70")); // 1970

669

console.log(moment.parseTwoDigitYear("99")); // 1999

670

671

// Practical usage for date parsing

672

function parseFlexibleDate(dateString) {

673

// Handle various date formats including 2-digit years

674

const formats = [

675

"YYYY-MM-DD",

676

"MM/DD/YYYY",

677

"DD/MM/YYYY",

678

"MM/DD/YY",

679

"DD/MM/YY",

680

"YY-MM-DD"

681

];

682

683

for (const format of formats) {

684

const parsed = moment(dateString, format, true);

685

if (parsed.isValid()) {

686

return parsed;

687

}

688

}

689

690

return moment.invalid();

691

}

692

693

// Test with various formats

694

console.log(parseFlexibleDate("2023-12-25").format("YYYY-MM-DD")); // "2023-12-25"

695

console.log(parseFlexibleDate("12/25/23").format("YYYY-MM-DD")); // "2023-12-25"

696

console.log(parseFlexibleDate("25/12/80").format("YYYY-MM-DD")); // "1980-12-25"

697

698

// Custom two-digit year logic

699

function customParseTwoDigitYear(input) {

700

const year = parseInt(input, 10);

701

const currentYear = moment().year();

702

const currentCentury = Math.floor(currentYear / 100) * 100;

703

704

// If year is within 20 years of current, assume same century

705

if (Math.abs((currentCentury + year) - currentYear) <= 20) {

706

return currentCentury + year;

707

}

708

709

// Otherwise use previous century

710

return currentCentury - 100 + year;

711

}

712

713

// Compare with moment's logic

714

const testYears = ["00", "23", "50", "80", "99"];

715

testYears.forEach(year => {

716

console.log(`${year}: moment=${moment.parseTwoDigitYear(year)}, custom=${customParseTwoDigitYear(year)}`);

717

});

718

```

719

720

## Version Information

721

722

Access to library version and prototype information.

723

724

```javascript { .api }

725

/**

726

* Current version of moment.js

727

*/

728

const version: string; // "2.30.1"

729

730

/**

731

* Reference to the Moment prototype

732

* Useful for extending Moment functionality

733

*/

734

const fn: Moment;

735

```

736

737

**Usage Examples:**

738

739

```javascript

740

import moment from "moment";

741

742

// Check version

743

console.log(moment.version); // "2.30.1"

744

745

// Version comparison for compatibility

746

function checkMomentVersion(requiredVersion) {

747

const current = moment.version.split('.').map(Number);

748

const required = requiredVersion.split('.').map(Number);

749

750

for (let i = 0; i < Math.max(current.length, required.length); i++) {

751

const currentPart = current[i] || 0;

752

const requiredPart = required[i] || 0;

753

754

if (currentPart > requiredPart) return 1;

755

if (currentPart < requiredPart) return -1;

756

}

757

758

return 0;

759

}

760

761

console.log(checkMomentVersion("2.29.0")); // 1 (current is newer)

762

console.log(checkMomentVersion("2.30.1")); // 0 (same version)

763

console.log(checkMomentVersion("2.31.0")); // -1 (required is newer)

764

765

// Extend Moment prototype (add custom methods)

766

moment.fn.toBusinessDay = function() {

767

const day = this.day();

768

if (day === 0) { // Sunday

769

return this.clone().add(1, 'day');

770

} else if (day === 6) { // Saturday

771

return this.clone().add(2, 'days');

772

}

773

return this.clone();

774

};

775

776

// Use custom method

777

const weekend = moment("2023-12-24"); // Sunday

778

const businessDay = weekend.toBusinessDay();

779

console.log(businessDay.format("dddd, YYYY-MM-DD")); // "Monday, 2023-12-25"

780

781

// Add validation method

782

moment.fn.isBusinessDay = function() {

783

const day = this.day();

784

return day >= 1 && day <= 5; // Monday to Friday

785

};

786

787

console.log(moment("2023-12-25").isBusinessDay()); // true (Monday)

788

console.log(moment("2023-12-24").isBusinessDay()); // false (Sunday)

789

790

// Add formatting shortcut

791

moment.fn.toShortString = function() {

792

return this.format("MMM D, YYYY");

793

};

794

795

console.log(moment("2023-12-25").toShortString()); // "Dec 25, 2023"

796

```

797

798

### Global Configuration Properties

799

800

Global configuration properties that control Moment.js behavior across all instances.

801

802

```javascript { .api }

803

/**

804

* Default format string used when no format is specified

805

* Can be modified to change global default formatting behavior

806

*/

807

let defaultFormat: string;

808

809

/**

810

* Default format string used for UTC moments when no format is specified

811

* Can be modified to change global UTC formatting behavior

812

*/

813

let defaultFormatUtc: string;

814

815

/**

816

* Controls whether deprecation warnings are printed to console

817

* Set to true to suppress all deprecation warnings

818

*/

819

let suppressDeprecationWarnings: boolean;

820

821

/**

822

* Custom handler function for deprecation warnings

823

* Called when deprecated methods are used (if suppressDeprecationWarnings is false)

824

* @param name - Name of the deprecated method (may be undefined)

825

* @param msg - Deprecation message explaining the issue

826

*/

827

let deprecationHandler: ((name: string | void, msg: string) => void) | void;

828

```

829

830

**Usage Examples:**

831

832

```javascript

833

import moment from "moment";

834

835

// Configure default formatting

836

moment.defaultFormat = "YYYY-MM-DD HH:mm:ss";

837

moment.defaultFormatUtc = "YYYY-MM-DD[T]HH:mm:ss[Z]";

838

839

console.log(moment().format()); // Uses defaultFormat

840

console.log(moment.utc().format()); // Uses defaultFormatUtc

841

842

// Handle deprecation warnings

843

moment.suppressDeprecationWarnings = false;

844

moment.deprecationHandler = function(name, msg) {

845

console.warn(`DEPRECATION WARNING - ${name}: ${msg}`);

846

// Could also send to logging service, etc.

847

};

848

849

// This would trigger the deprecation handler

850

const m = moment();

851

m.zone(); // Deprecated method - would call deprecationHandler

852

853

// Suppress all deprecation warnings in production

854

if (process.env.NODE_ENV === 'production') {

855

moment.suppressDeprecationWarnings = true;

856

}

857

858

// Custom deprecation handling for development

859

if (process.env.NODE_ENV === 'development') {

860

moment.deprecationHandler = function(name, msg) {

861

console.error(`🚨 Moment.js Deprecation: ${name || 'Unknown method'}`);

862

console.error(`πŸ“– Details: ${msg}`);

863

console.error(`πŸ”— See: https://momentjs.com/docs/#/parsing/string/`);

864

865

// Optionally throw in strict development mode

866

if (process.env.STRICT_DEPRECATION) {

867

throw new Error(`Deprecated Moment.js method used: ${name}`);

868

}

869

};

870

}

871

872

// Reset to defaults

873

moment.defaultFormat = undefined; // Uses built-in default

874

moment.defaultFormatUtc = undefined; // Uses built-in default

875

moment.suppressDeprecationWarnings = false;

876

moment.deprecationHandler = undefined;

877

```

878

879

### Deprecated Methods

880

881

Methods that have been deprecated and should not be used in new code. These are documented for completeness but are not recommended for use.

882

883

```javascript { .api }

884

/**

885

* @deprecated This method has been deprecated because it has no reliable implementation.

886

* DST shift detection is complex and error-prone across different timezones and years.

887

* Use timezone-aware libraries like moment-timezone for reliable DST handling.

888

* @returns boolean indicating DST shift (unreliable)

889

*/

890

isDSTShifted(): boolean;

891

```

892

893

**Migration Guidance:**

894

895

```javascript

896

import moment from "moment";

897

898

// ❌ Deprecated - don't use

899

const isShifted = moment().isDSTShifted(); // Unreliable

900

901

// βœ… Better alternatives:

902

903

// Option 1: Use moment-timezone for reliable DST detection

904

// npm install moment-timezone

905

import momentTz from "moment-timezone";

906

const nyTime = momentTz.tz("America/New_York");

907

const isDST = nyTime.isDST();

908

909

// Option 2: Use built-in isDST() method for current moment

910

const currentDST = moment().isDST(); // Reliable for current moment

911

912

// Option 3: For timezone-aware applications, use newer libraries

913

// Consider migrating to:

914

// - date-fns-tz for timezone support

915

// - Luxon for comprehensive timezone and DST handling

916

// - Temporal (future JS standard) when available

917

918

// Example timezone-aware DST check with better approach

919

function checkDSTStatus(date, timezone) {

920

// This requires moment-timezone or similar library

921

if (typeof momentTz !== 'undefined' && momentTz.tz) {

922

return momentTz.tz(date, timezone).isDST();

923

}

924

925

// Fallback to basic DST check (less reliable)

926

return moment(date).isDST();

927

}

928

929

// Usage with proper timezone handling

930

const winterDate = "2023-01-15";

931

const summerDate = "2023-07-15";

932

933

console.log(`Winter DST: ${checkDSTStatus(winterDate, "America/New_York")}`);

934

console.log(`Summer DST: ${checkDSTStatus(summerDate, "America/New_York")}`);

935

```