Parse, validate, manipulate, and display dates and times in JavaScript with internationalization support
—
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Pending
The risk profile of this skill
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.
Static methods for determining the type of values, particularly useful for type guards and validation.
/**
* Check if a value is a Moment instance
* @param m - Value to check
* @returns true if value is a Moment instance, false otherwise
*/
function isMoment(m: any): m is Moment;
/**
* Check if a value is a native Date instance
* @param m - Value to check
* @returns true if value is a Date instance, false otherwise
*/
function isDate(m: any): m is Date;
/**
* Check if a value is a Duration instance
* @param d - Value to check
* @returns true if value is a Duration instance, false otherwise
*/
function isDuration(d: any): d is Duration;Usage Examples:
import moment from "moment";
const momentObj = moment();
const dateObj = new Date();
const durationObj = moment.duration(2, "hours");
const stringValue = "2023-12-25";
const numberValue = 1640447400000;
const plainObject = { year: 2023, month: 11, day: 25 };
// Type checking
console.log(moment.isMoment(momentObj)); // true
console.log(moment.isMoment(dateObj)); // false
console.log(moment.isMoment(stringValue)); // false
console.log(moment.isMoment(numberValue)); // false
console.log(moment.isDate(dateObj)); // true
console.log(moment.isDate(momentObj)); // false
console.log(moment.isDate(stringValue)); // false
console.log(moment.isDuration(durationObj)); // true
console.log(moment.isDuration(momentObj)); // false
console.log(moment.isDuration(numberValue)); // false
// Practical usage in functions
function safeMoment(input) {
if (moment.isMoment(input)) {
return input.clone(); // Already a moment, clone to avoid mutation
} else if (moment.isDate(input)) {
return moment(input); // Convert Date to Moment
} else {
return moment(input); // Parse string/number/etc
}
}
function formatAnyDate(input) {
const momentInstance = safeMoment(input);
return momentInstance.format("YYYY-MM-DD");
}
// Type guards in conditional logic
function processTimeValue(value) {
if (moment.isMoment(value)) {
return value.format("YYYY-MM-DD HH:mm:ss");
} else if (moment.isDate(value)) {
return moment(value).format("YYYY-MM-DD HH:mm:ss");
} else if (moment.isDuration(value)) {
return value.humanize();
} else {
return "Invalid time value";
}
}
// Array filtering with type checks
const mixedArray = [
moment(),
new Date(),
moment.duration(2, "hours"),
"2023-12-25",
123456789
];
const onlyMoments = mixedArray.filter(moment.isMoment);
const onlyDates = mixedArray.filter(moment.isDate);
const onlyDurations = mixedArray.filter(moment.isDuration);
console.log(onlyMoments.length); // 1
console.log(onlyDates.length); // 1
console.log(onlyDurations.length); // 1Find the earliest or latest moment from a collection of moments.
/**
* Find the earliest (minimum) moment from an array
* @param moments - Array of moments to compare
* @returns The earliest moment from the array
*/
function min(moments: Moment[]): Moment;
/**
* Find the earliest (minimum) moment from variable arguments
* @param moments - Variable number of moment arguments
* @returns The earliest moment from the arguments
*/
function min(...moments: Moment[]): Moment;
/**
* Find the latest (maximum) moment from an array
* @param moments - Array of moments to compare
* @returns The latest moment from the array
*/
function max(moments: Moment[]): Moment;
/**
* Find the latest (maximum) moment from variable arguments
* @param moments - Variable number of moment arguments
* @returns The latest moment from the arguments
*/
function max(...moments: Moment[]): Moment;Usage Examples:
import moment from "moment";
// Create array of moments
const dates = [
moment("2023-12-25"),
moment("2023-01-15"),
moment("2023-06-30"),
moment("2023-03-10"),
moment("2023-11-05")
];
// Find min and max from array
const earliest = moment.min(dates);
const latest = moment.max(dates);
console.log(earliest.format("YYYY-MM-DD")); // "2023-01-15"
console.log(latest.format("YYYY-MM-DD")); // "2023-12-25"
// Using variable arguments
const min1 = moment.min(
moment("2023-01-01"),
moment("2023-06-15"),
moment("2023-03-20")
);
console.log(min1.format("YYYY-MM-DD")); // "2023-01-01"
const max1 = moment.max(
moment("2023-01-01"),
moment("2023-06-15"),
moment("2023-03-20")
);
console.log(max1.format("YYYY-MM-DD")); // "2023-06-15"
// Practical examples
function getDateRange(appointments) {
const moments = appointments.map(apt => moment(apt.date));
return {
start: moment.min(moments),
end: moment.max(moments)
};
}
const appointments = [
{ date: "2023-12-25T10:00:00", title: "Meeting 1" },
{ date: "2023-12-20T14:30:00", title: "Meeting 2" },
{ date: "2023-12-30T09:00:00", title: "Meeting 3" }
];
const range = getDateRange(appointments);
console.log(`Appointments from ${range.start.format("MMM D")} to ${range.end.format("MMM D")}`);
// "Appointments from Dec 20 to Dec 30"
// Handle empty arrays safely
function safeMin(moments) {
if (moments.length === 0) {
return null;
}
return moment.min(moments);
}
function safeMax(moments) {
if (moments.length === 0) {
return null;
}
return moment.max(moments);
}
// Find business hours range
const workTimes = [
moment("2023-12-25T09:00:00"),
moment("2023-12-25T12:30:00"),
moment("2023-12-25T17:00:00"),
moment("2023-12-25T08:30:00")
];
const workStart = moment.min(workTimes);
const workEnd = moment.max(workTimes);
console.log(`Work day: ${workStart.format("HH:mm")} to ${workEnd.format("HH:mm")}`);
// "Work day: 08:30 to 17:00"Get the current time in milliseconds, with ability to override for testing.
/**
* Get the current time in milliseconds since Unix epoch
* This function can be overridden for testing purposes
* @returns Current time in milliseconds
*/
function now(): number;Usage Examples:
import moment from "moment";
// Get current timestamp
const currentTime = moment.now();
console.log(currentTime); // e.g., 1703517045123
// Same as Date.now() and +moment()
console.log(moment.now() === Date.now()); // approximately true (within milliseconds)
console.log(moment.now() === +moment()); // approximately true
// Override for testing (useful in test environments)
const originalNow = moment.now;
moment.now = function() {
return moment("2023-12-25T15:30:00").valueOf();
};
console.log(moment().format()); // Always returns "2023-12-25T15:30:00..."
// Restore original function
moment.now = originalNow;
// Practical usage for timestamps
function logEvent(message) {
const timestamp = moment.now();
const readable = moment(timestamp).format("YYYY-MM-DD HH:mm:ss");
console.log(`[${readable}] ${message}`);
}
logEvent("User logged in"); // [2023-12-25 15:30:45] User logged in
// Performance timing
const startTime = moment.now();
// ... some operation ...
const endTime = moment.now();
const duration = moment.duration(endTime - startTime);
console.log(`Operation took ${duration.asMilliseconds()}ms`);Create explicitly invalid moments for error handling and testing.
/**
* Create an explicitly invalid Moment instance
* @param flags - Optional parsing flags for debugging invalid state
* @returns Invalid Moment instance
*/
function invalid(flags?: MomentParsingFlagsOpt): Moment;
interface MomentParsingFlagsOpt {
empty?: boolean;
unusedTokens?: string[];
unusedInput?: string[];
overflow?: number;
charsLeftOver?: number;
nullInput?: boolean;
invalidMonth?: string;
invalidFormat?: boolean;
userInvalidated?: boolean;
iso?: boolean;
parsedDateParts?: any[];
meridiem?: string;
}Usage Examples:
import moment from "moment";
// Create invalid moment
const invalidMoment = moment.invalid();
console.log(invalidMoment.isValid()); // false
console.log(invalidMoment.format()); // "Invalid date"
// Create invalid moment with debugging info
const invalidWithFlags = moment.invalid({
invalidFormat: true,
userInvalidated: true
});
const flags = invalidWithFlags.parsingFlags();
console.log(flags.invalidFormat); // true
console.log(flags.userInvalidated); // true
// Practical usage for error handling
function safeParseDateString(dateString) {
if (!dateString || typeof dateString !== 'string') {
return moment.invalid({ nullInput: true });
}
const parsed = moment(dateString, "YYYY-MM-DD", true); // strict parsing
if (!parsed.isValid()) {
return moment.invalid({ invalidFormat: true });
}
return parsed;
}
// Test the function
const validDate = safeParseDateString("2023-12-25");
const invalidDate = safeParseDateString("invalid-date");
const nullDate = safeParseDateString(null);
console.log(validDate.isValid()); // true
console.log(invalidDate.isValid()); // false
console.log(nullDate.isValid()); // false
// Handle invalid moments in processing
function processDate(input) {
const moment = safeParseDateString(input);
if (!moment.isValid()) {
const flags = moment.parsingFlags();
if (flags.nullInput) {
return { error: "No input provided" };
} else if (flags.invalidFormat) {
return { error: "Invalid date format" };
} else {
return { error: "Unknown parsing error" };
}
}
return { date: moment.format("YYYY-MM-DD") };
}
console.log(processDate("2023-12-25")); // { date: "2023-12-25" }
console.log(processDate("invalid")); // { error: "Invalid date format" }
console.log(processDate(null)); // { error: "No input provided" }Normalize time unit strings to canonical forms.
/**
* Normalize a time unit string to its canonical form
* @param unit - Time unit string to normalize
* @returns Normalized unit string, or null if invalid
*/
function normalizeUnits(unit: unitOfTime.All): string;Usage Examples:
import moment from "moment";
// Normalize various unit strings
console.log(moment.normalizeUnits("year")); // "year"
console.log(moment.normalizeUnits("years")); // "year"
console.log(moment.normalizeUnits("y")); // "year"
console.log(moment.normalizeUnits("Y")); // "year"
console.log(moment.normalizeUnits("month")); // "month"
console.log(moment.normalizeUnits("months")); // "month"
console.log(moment.normalizeUnits("M")); // "month"
console.log(moment.normalizeUnits("day")); // "day"
console.log(moment.normalizeUnits("days")); // "day"
console.log(moment.normalizeUnits("d")); // "day"
console.log(moment.normalizeUnits("hour")); // "hour"
console.log(moment.normalizeUnits("hours")); // "hour"
console.log(moment.normalizeUnits("h")); // "hour"
console.log(moment.normalizeUnits("minute")); // "minute"
console.log(moment.normalizeUnits("minutes")); // "minute"
console.log(moment.normalizeUnits("m")); // "minute"
console.log(moment.normalizeUnits("second")); // "second"
console.log(moment.normalizeUnits("seconds")); // "second"
console.log(moment.normalizeUnits("s")); // "second"
console.log(moment.normalizeUnits("millisecond")); // "millisecond"
console.log(moment.normalizeUnits("milliseconds")); // "millisecond"
console.log(moment.normalizeUnits("ms")); // "millisecond"
// Special units
console.log(moment.normalizeUnits("quarter")); // "quarter"
console.log(moment.normalizeUnits("Q")); // "quarter"
console.log(moment.normalizeUnits("week")); // "week"
console.log(moment.normalizeUnits("w")); // "week"
console.log(moment.normalizeUnits("isoWeek")); // "isoWeek"
console.log(moment.normalizeUnits("W")); // "isoWeek"
// Invalid units return null
console.log(moment.normalizeUnits("invalid")); // null
console.log(moment.normalizeUnits("")); // null
// Practical usage
function createFlexibleDuration(amount, unit) {
const normalizedUnit = moment.normalizeUnits(unit);
if (!normalizedUnit) {
throw new Error(`Invalid time unit: ${unit}`);
}
return moment.duration(amount, normalizedUnit);
}
// All of these work the same way
const duration1 = createFlexibleDuration(2, "hour");
const duration2 = createFlexibleDuration(2, "hours");
const duration3 = createFlexibleDuration(2, "h");
console.log(duration1.asHours()); // 2
console.log(duration2.asHours()); // 2
console.log(duration3.asHours()); // 2
// Validation function
function isValidTimeUnit(unit) {
return moment.normalizeUnits(unit) !== null;
}
console.log(isValidTimeUnit("days")); // true
console.log(isValidTimeUnit("invalid")); // falseConfigure global settings for relative time display and thresholds.
/**
* Get current relative time threshold for a unit
* @param threshold - Threshold identifier ("ss", "s", "m", "h", "d", "M")
* @returns Current threshold value or boolean indicating if set
*/
function relativeTimeThreshold(threshold: string): number | boolean;
/**
* Set relative time threshold for a unit
* @param threshold - Threshold identifier to set
* @param limit - New threshold value
* @returns true if threshold was set successfully
*/
function relativeTimeThreshold(threshold: string, limit: number): boolean;
/**
* Get current relative time rounding function
* @returns Current rounding function
*/
function relativeTimeRounding(): (num: number) => number;
/**
* Set relative time rounding function
* @param fn - Function to use for rounding relative time values
* @returns true if rounding function was set successfully
*/
function relativeTimeRounding(fn: (num: number) => number): boolean;Usage Examples:
import moment from "moment";
// Get current thresholds
console.log(moment.relativeTimeThreshold("ss")); // 44 (seconds to show "a few seconds")
console.log(moment.relativeTimeThreshold("s")); // 45 (seconds to show "a minute")
console.log(moment.relativeTimeThreshold("m")); // 45 (minutes to show "an hour")
console.log(moment.relativeTimeThreshold("h")); // 22 (hours to show "a day")
console.log(moment.relativeTimeThreshold("d")); // 26 (days to show "a month")
console.log(moment.relativeTimeThreshold("M")); // 11 (months to show "a year")
// Test default behavior
const test1 = moment().subtract(30, "seconds");
const test2 = moment().subtract(50, "seconds");
console.log(test1.fromNow()); // "a few seconds ago"
console.log(test2.fromNow()); // "a minute ago"
// Customize thresholds
moment.relativeTimeThreshold("ss", 10); // Show "a few seconds" only for <= 10 seconds
moment.relativeTimeThreshold("s", 60); // Show "a minute" up to 60 seconds
const test3 = moment().subtract(30, "seconds");
console.log(test3.fromNow()); // "30 seconds ago" (now shows specific seconds)
// Reset thresholds
moment.relativeTimeThreshold("ss", 44);
moment.relativeTimeThreshold("s", 45);
// Custom rounding function
const originalRounding = moment.relativeTimeRounding();
console.log(originalRounding(2.6)); // 3 (default rounds normally)
// Set custom rounding (always floor)
moment.relativeTimeRounding(Math.floor);
const testRounding = moment().subtract(2.8, "hours");
console.log(testRounding.fromNow()); // Uses floor rounding
// Set custom rounding (always ceiling)
moment.relativeTimeRounding(Math.ceil);
// Restore original rounding
moment.relativeTimeRounding(originalRounding);
// Practical example: more precise relative times
function configurePreciseRelativeTime() {
// Show exact seconds for first minute
moment.relativeTimeThreshold("ss", 0); // Never show "a few seconds"
moment.relativeTimeThreshold("s", 60); // Show seconds up to 60
// Show exact minutes for first hour
moment.relativeTimeThreshold("m", 60); // Show minutes up to 60
// Show exact hours for first day
moment.relativeTimeThreshold("h", 24); // Show hours up to 24
}
configurePreciseRelativeTime();
const now = moment();
console.log(now.clone().subtract(30, "seconds").fromNow()); // "30 seconds ago"
console.log(now.clone().subtract(45, "minutes").fromNow()); // "45 minutes ago"
console.log(now.clone().subtract(12, "hours").fromNow()); // "12 hours ago"Get the calendar format string for displaying relationships between moments.
/**
* Get the calendar format string for the relationship between two moments
* @param m - The moment to format
* @param now - Reference moment (usually current time)
* @returns Calendar format key ("sameDay", "nextDay", etc.)
*/
function calendarFormat(m: Moment, now: Moment): string;Usage Examples:
import moment from "moment";
const now = moment("2023-12-25T15:30:00");
const today = moment("2023-12-25T10:00:00");
const tomorrow = moment("2023-12-26T10:00:00");
const yesterday = moment("2023-12-24T10:00:00");
const nextWeek = moment("2024-01-01T10:00:00");
const lastWeek = moment("2023-12-18T10:00:00");
const farFuture = moment("2024-06-15T10:00:00");
// Get calendar format keys
console.log(moment.calendarFormat(today, now)); // "sameDay"
console.log(moment.calendarFormat(tomorrow, now)); // "nextDay"
console.log(moment.calendarFormat(yesterday, now)); // "lastDay"
console.log(moment.calendarFormat(nextWeek, now)); // "nextWeek"
console.log(moment.calendarFormat(lastWeek, now)); // "lastWeek"
console.log(moment.calendarFormat(farFuture, now)); // "sameElse"
// Use with locale data to get format strings
const localeData = moment.localeData();
const formats = {
sameDay: localeData._config.calendar.sameDay,
nextDay: localeData._config.calendar.nextDay,
lastDay: localeData._config.calendar.lastDay,
nextWeek: localeData._config.calendar.nextWeek,
lastWeek: localeData._config.calendar.lastWeek,
sameElse: localeData._config.calendar.sameElse
};
console.log(formats);
// {
// sameDay: '[Today at] LT',
// nextDay: '[Tomorrow at] LT',
// lastDay: '[Yesterday at] LT',
// nextWeek: 'dddd [at] LT',
// lastWeek: '[Last] dddd [at] LT',
// sameElse: 'L'
// }
// Practical usage for custom calendar formatting
function customCalendarFormat(targetMoment, referenceMoment = moment()) {
const formatKey = moment.calendarFormat(targetMoment, referenceMoment);
const localeData = moment.localeData();
switch (formatKey) {
case "sameDay":
return targetMoment.format("[Today at] HH:mm");
case "nextDay":
return targetMoment.format("[Tomorrow at] HH:mm");
case "lastDay":
return targetMoment.format("[Yesterday at] HH:mm");
case "nextWeek":
return targetMoment.format("dddd [at] HH:mm");
case "lastWeek":
return targetMoment.format("[Last] dddd [at] HH:mm");
default:
return targetMoment.format("YYYY-MM-DD HH:mm");
}
}
console.log(customCalendarFormat(today, now)); // "Today at 10:00"
console.log(customCalendarFormat(tomorrow, now)); // "Tomorrow at 10:00"
console.log(customCalendarFormat(farFuture, now)); // "2024-06-15 10:00"Utility for parsing two-digit years with century logic.
/**
* Parse a two-digit year string into a four-digit year
* Years 00-68 are interpreted as 2000-2068
* Years 69-99 are interpreted as 1969-1999
* @param input - Two-digit year string
* @returns Four-digit year as number
*/
function parseTwoDigitYear(input: string): number;Usage Examples:
import moment from "moment";
// Parse two-digit years
console.log(moment.parseTwoDigitYear("00")); // 2000
console.log(moment.parseTwoDigitYear("01")); // 2001
console.log(moment.parseTwoDigitYear("23")); // 2023
console.log(moment.parseTwoDigitYear("68")); // 2068
console.log(moment.parseTwoDigitYear("69")); // 1969
console.log(moment.parseTwoDigitYear("70")); // 1970
console.log(moment.parseTwoDigitYear("99")); // 1999
// Practical usage for date parsing
function parseFlexibleDate(dateString) {
// Handle various date formats including 2-digit years
const formats = [
"YYYY-MM-DD",
"MM/DD/YYYY",
"DD/MM/YYYY",
"MM/DD/YY",
"DD/MM/YY",
"YY-MM-DD"
];
for (const format of formats) {
const parsed = moment(dateString, format, true);
if (parsed.isValid()) {
return parsed;
}
}
return moment.invalid();
}
// Test with various formats
console.log(parseFlexibleDate("2023-12-25").format("YYYY-MM-DD")); // "2023-12-25"
console.log(parseFlexibleDate("12/25/23").format("YYYY-MM-DD")); // "2023-12-25"
console.log(parseFlexibleDate("25/12/80").format("YYYY-MM-DD")); // "1980-12-25"
// Custom two-digit year logic
function customParseTwoDigitYear(input) {
const year = parseInt(input, 10);
const currentYear = moment().year();
const currentCentury = Math.floor(currentYear / 100) * 100;
// If year is within 20 years of current, assume same century
if (Math.abs((currentCentury + year) - currentYear) <= 20) {
return currentCentury + year;
}
// Otherwise use previous century
return currentCentury - 100 + year;
}
// Compare with moment's logic
const testYears = ["00", "23", "50", "80", "99"];
testYears.forEach(year => {
console.log(`${year}: moment=${moment.parseTwoDigitYear(year)}, custom=${customParseTwoDigitYear(year)}`);
});Access to library version and prototype information.
/**
* Current version of moment.js
*/
const version: string; // "2.30.1"
/**
* Reference to the Moment prototype
* Useful for extending Moment functionality
*/
const fn: Moment;Usage Examples:
import moment from "moment";
// Check version
console.log(moment.version); // "2.30.1"
// Version comparison for compatibility
function checkMomentVersion(requiredVersion) {
const current = moment.version.split('.').map(Number);
const required = requiredVersion.split('.').map(Number);
for (let i = 0; i < Math.max(current.length, required.length); i++) {
const currentPart = current[i] || 0;
const requiredPart = required[i] || 0;
if (currentPart > requiredPart) return 1;
if (currentPart < requiredPart) return -1;
}
return 0;
}
console.log(checkMomentVersion("2.29.0")); // 1 (current is newer)
console.log(checkMomentVersion("2.30.1")); // 0 (same version)
console.log(checkMomentVersion("2.31.0")); // -1 (required is newer)
// Extend Moment prototype (add custom methods)
moment.fn.toBusinessDay = function() {
const day = this.day();
if (day === 0) { // Sunday
return this.clone().add(1, 'day');
} else if (day === 6) { // Saturday
return this.clone().add(2, 'days');
}
return this.clone();
};
// Use custom method
const weekend = moment("2023-12-24"); // Sunday
const businessDay = weekend.toBusinessDay();
console.log(businessDay.format("dddd, YYYY-MM-DD")); // "Monday, 2023-12-25"
// Add validation method
moment.fn.isBusinessDay = function() {
const day = this.day();
return day >= 1 && day <= 5; // Monday to Friday
};
console.log(moment("2023-12-25").isBusinessDay()); // true (Monday)
console.log(moment("2023-12-24").isBusinessDay()); // false (Sunday)
// Add formatting shortcut
moment.fn.toShortString = function() {
return this.format("MMM D, YYYY");
};
console.log(moment("2023-12-25").toShortString()); // "Dec 25, 2023"Global configuration properties that control Moment.js behavior across all instances.
/**
* Default format string used when no format is specified
* Can be modified to change global default formatting behavior
*/
let defaultFormat: string;
/**
* Default format string used for UTC moments when no format is specified
* Can be modified to change global UTC formatting behavior
*/
let defaultFormatUtc: string;
/**
* Controls whether deprecation warnings are printed to console
* Set to true to suppress all deprecation warnings
*/
let suppressDeprecationWarnings: boolean;
/**
* Custom handler function for deprecation warnings
* Called when deprecated methods are used (if suppressDeprecationWarnings is false)
* @param name - Name of the deprecated method (may be undefined)
* @param msg - Deprecation message explaining the issue
*/
let deprecationHandler: ((name: string | void, msg: string) => void) | void;Usage Examples:
import moment from "moment";
// Configure default formatting
moment.defaultFormat = "YYYY-MM-DD HH:mm:ss";
moment.defaultFormatUtc = "YYYY-MM-DD[T]HH:mm:ss[Z]";
console.log(moment().format()); // Uses defaultFormat
console.log(moment.utc().format()); // Uses defaultFormatUtc
// Handle deprecation warnings
moment.suppressDeprecationWarnings = false;
moment.deprecationHandler = function(name, msg) {
console.warn(`DEPRECATION WARNING - ${name}: ${msg}`);
// Could also send to logging service, etc.
};
// This would trigger the deprecation handler
const m = moment();
m.zone(); // Deprecated method - would call deprecationHandler
// Suppress all deprecation warnings in production
if (process.env.NODE_ENV === 'production') {
moment.suppressDeprecationWarnings = true;
}
// Custom deprecation handling for development
if (process.env.NODE_ENV === 'development') {
moment.deprecationHandler = function(name, msg) {
console.error(`🚨 Moment.js Deprecation: ${name || 'Unknown method'}`);
console.error(`📖 Details: ${msg}`);
console.error(`🔗 See: https://momentjs.com/docs/#/parsing/string/`);
// Optionally throw in strict development mode
if (process.env.STRICT_DEPRECATION) {
throw new Error(`Deprecated Moment.js method used: ${name}`);
}
};
}
// Reset to defaults
moment.defaultFormat = undefined; // Uses built-in default
moment.defaultFormatUtc = undefined; // Uses built-in default
moment.suppressDeprecationWarnings = false;
moment.deprecationHandler = undefined;Methods that have been deprecated and should not be used in new code. These are documented for completeness but are not recommended for use.
/**
* @deprecated This method has been deprecated because it has no reliable implementation.
* DST shift detection is complex and error-prone across different timezones and years.
* Use timezone-aware libraries like moment-timezone for reliable DST handling.
* @returns boolean indicating DST shift (unreliable)
*/
isDSTShifted(): boolean;Migration Guidance:
import moment from "moment";
// ❌ Deprecated - don't use
const isShifted = moment().isDSTShifted(); // Unreliable
// ✅ Better alternatives:
// Option 1: Use moment-timezone for reliable DST detection
// npm install moment-timezone
import momentTz from "moment-timezone";
const nyTime = momentTz.tz("America/New_York");
const isDST = nyTime.isDST();
// Option 2: Use built-in isDST() method for current moment
const currentDST = moment().isDST(); // Reliable for current moment
// Option 3: For timezone-aware applications, use newer libraries
// Consider migrating to:
// - date-fns-tz for timezone support
// - Luxon for comprehensive timezone and DST handling
// - Temporal (future JS standard) when available
// Example timezone-aware DST check with better approach
function checkDSTStatus(date, timezone) {
// This requires moment-timezone or similar library
if (typeof momentTz !== 'undefined' && momentTz.tz) {
return momentTz.tz(date, timezone).isDST();
}
// Fallback to basic DST check (less reliable)
return moment(date).isDST();
}
// Usage with proper timezone handling
const winterDate = "2023-01-15";
const summerDate = "2023-07-15";
console.log(`Winter DST: ${checkDSTStatus(winterDate, "America/New_York")}`);
console.log(`Summer DST: ${checkDSTStatus(summerDate, "America/New_York")}`);