CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-moment

Parse, validate, manipulate, and display dates and times in JavaScript with internationalization support

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

comparison-validation.mddocs/

Comparison and Validation

Methods for comparing Moment instances, validating dates, and determining relationships between different time points with optional granularity control.

Capabilities

Basic Comparison Methods

Core comparison methods for determining temporal relationships between moments.

/**
 * Check if this moment is before another moment
 * @param inp - Moment to compare against (defaults to now)
 * @param granularity - Unit of comparison (year, month, day, etc.)
 * @returns true if this moment is before the input
 */
isBefore(inp?: MomentInput, granularity?: unitOfTime.StartOf): boolean;

/**
 * Check if this moment is after another moment
 * @param inp - Moment to compare against (defaults to now)
 * @param granularity - Unit of comparison (year, month, day, etc.)
 * @returns true if this moment is after the input
 */
isAfter(inp?: MomentInput, granularity?: unitOfTime.StartOf): boolean;

/**
 * Check if this moment is the same as another moment
 * @param inp - Moment to compare against (defaults to now)
 * @param granularity - Unit of comparison (year, month, day, etc.)
 * @returns true if this moment is the same as the input
 */
isSame(inp?: MomentInput, granularity?: unitOfTime.StartOf): boolean;

/**
 * Check if this moment is same or after another moment
 * @param inp - Moment to compare against (defaults to now)
 * @param granularity - Unit of comparison (year, month, day, etc.)
 * @returns true if this moment is same or after the input
 */
isSameOrAfter(inp?: MomentInput, granularity?: unitOfTime.StartOf): boolean;

/**
 * Check if this moment is same or before another moment
 * @param inp - Moment to compare against (defaults to now)
 * @param granularity - Unit of comparison (year, month, day, etc.)
 * @returns true if this moment is same or before the input
 */
isSameOrBefore(inp?: MomentInput, granularity?: unitOfTime.StartOf): boolean;

Usage Examples:

import moment from "moment";

const date1 = moment("2023-12-25T15:30:00");
const date2 = moment("2023-12-26T10:00:00");
const date3 = moment("2023-12-25T20:00:00");

// Basic comparisons (exact time)
console.log(date1.isBefore(date2)); // true
console.log(date1.isAfter(date2)); // false
console.log(date1.isSame(date1.clone())); // true
console.log(date1.isSameOrAfter(date1.clone())); // true
console.log(date1.isSameOrBefore(date2)); // true

// Compare with now (no argument)
console.log(moment("2020-01-01").isBefore()); // true (before now)
console.log(moment("2030-01-01").isAfter()); // true (after now)

// Granularity comparisons
console.log(date1.isSame(date3, "day")); // true (same day, different time)
console.log(date1.isSame(date3, "hour")); // false (different hour)
console.log(date1.isBefore(date2, "year")); // false (same year)
console.log(date1.isBefore(date2, "day")); // true (different day)

// Month/year granularity
const jan2023 = moment("2023-01-15");
const feb2023 = moment("2023-02-20");
const jan2024 = moment("2024-01-10");

console.log(jan2023.isBefore(feb2023, "month")); // true
console.log(jan2023.isSame(jan2024, "month")); // false (different year)
console.log(jan2023.isSame(jan2024, "year")); // false

Range Comparison

Check if a moment falls within a range between two other moments.

/**
 * Check if this moment is between two other moments
 * @param a - Start of range
 * @param b - End of range  
 * @param granularity - Unit of comparison (optional)
 * @param inclusivity - Include or exclude endpoints ("()", "[)", "(]", "[]")
 * @returns true if this moment is between a and b
 */
isBetween(
  a: MomentInput, 
  b: MomentInput, 
  granularity?: unitOfTime.StartOf, 
  inclusivity?: "()" | "[)" | "(]" | "[]"
): boolean;

Usage Examples:

import moment from "moment";

const start = moment("2023-12-20");
const middle = moment("2023-12-25");
const end = moment("2023-12-30");

// Basic range check (exclusive by default)
console.log(middle.isBetween(start, end)); // true

// Inclusivity options
console.log(start.isBetween(start, end, null, "()")); // false (exclusive)
console.log(start.isBetween(start, end, null, "[)")); // true (include start)
console.log(end.isBetween(start, end, null, "(]")); // true (include end)
console.log(start.isBetween(start, end, null, "[]")); // true (include both)
console.log(end.isBetween(start, end, null, "[]")); // true (include both)

// With granularity
const time1 = moment("2023-12-25T10:00:00");
const time2 = moment("2023-12-25T15:00:00");
const time3 = moment("2023-12-25T20:00:00");

console.log(time2.isBetween(time1, time3, "hour")); // true
console.log(time2.isBetween(time1, time3, "day")); // false (same day)

// Date range examples
const workStart = moment("2023-12-25T09:00:00");
const workEnd = moment("2023-12-25T17:00:00");
const lunchTime = moment("2023-12-25T12:30:00");

console.log(lunchTime.isBetween(workStart, workEnd)); // true
console.log(lunchTime.isBetween(workStart, workEnd, "hour")); // true

Difference Calculations

Calculate the difference between two moments in various units.

/**
 * Get the difference between this moment and another
 * @param b - Moment to calculate difference from
 * @param unitOfTime - Unit to return difference in (defaults to milliseconds)
 * @param precise - Return floating point result (default: false for integer)
 * @returns Difference as number (positive if this moment is after input)
 */
diff(b: MomentInput, unitOfTime?: unitOfTime.Diff, precise?: boolean): number;

// Diff units
type Diff = "year" | "years" | "y" |
            "quarter" | "quarters" | "Q" |
            "month" | "months" | "M" |
            "week" | "weeks" | "w" |
            "day" | "days" | "d" |
            "hour" | "hours" | "h" |
            "minute" | "minutes" | "m" |
            "second" | "seconds" | "s" |
            "millisecond" | "milliseconds" | "ms";

Usage Examples:

import moment from "moment";

const start = moment("2023-12-25T10:00:00");
const end = moment("2023-12-25T15:30:00");

// Default (milliseconds)
console.log(end.diff(start)); // 19800000 (5.5 hours in milliseconds)

// Different units
console.log(end.diff(start, "hours")); // 5 (integer hours)
console.log(end.diff(start, "hours", true)); // 5.5 (precise hours)
console.log(end.diff(start, "minutes")); // 330 (minutes)
console.log(end.diff(start, "seconds")); // 19800 (seconds)

// Date differences
const birthday = moment("1990-06-15");
const now = moment("2023-12-25");

console.log(now.diff(birthday, "years")); // 33 (age in years)
console.log(now.diff(birthday, "years", true)); // 33.53... (precise years)
console.log(now.diff(birthday, "months")); // 402 (months)
console.log(now.diff(birthday, "days")); // 12246 (days)

// Negative differences (past vs future)
console.log(start.diff(end, "hours")); // -5 (negative because start is before end)

// Week and quarter differences
const q1Start = moment("2023-01-01");
const q2Start = moment("2023-04-01");
const q4Start = moment("2023-10-01");

console.log(q2Start.diff(q1Start, "quarters")); // 1
console.log(q4Start.diff(q1Start, "quarters")); // 3
console.log(q2Start.diff(q1Start, "weeks")); // ~13 weeks

// Practical examples
const projectStart = moment("2023-01-01");
const projectEnd = moment("2023-06-15");
const daysRemaining = projectEnd.diff(moment(), "days");
const weeksElapsed = moment().diff(projectStart, "weeks");

Validation Methods

Methods for validating moment instances and checking their state.

/**
 * Check if this moment represents a valid date/time
 * @returns true if valid, false otherwise
 */
isValid(): boolean;

/**
 * Get the index of the invalid field (for debugging)
 * @returns Index of invalid field, or -1 if valid
 */
invalidAt(): number;

/**
 * Get creation metadata for this moment
 * @returns Object containing input, format, locale, and creation details
 */
creationData(): MomentCreationData;

/**
 * Get parsing flags (for debugging parsing issues)
 * @returns Object containing detailed parsing information
 */
parsingFlags(): MomentParsingFlags;

interface MomentCreationData {
  input: MomentInput;
  format?: MomentFormatSpecification;
  locale: Locale;
  isUTC: boolean;
  strict?: boolean;
}

interface MomentParsingFlags {
  empty: boolean;
  unusedTokens: string[];
  unusedInput: string[];
  overflow: number;
  charsLeftOver: number;
  nullInput: boolean;
  invalidMonth: string | void;
  invalidFormat: boolean;
  userInvalidated: boolean;
  iso: boolean;
  parsedDateParts: any[];
  meridiem: string | void;
}

Usage Examples:

import moment from "moment";

// Valid moments
const validDate = moment("2023-12-25");
console.log(validDate.isValid()); // true
console.log(validDate.invalidAt()); // -1 (no invalid field)

// Invalid moments
const invalidDate = moment("2023-13-45"); // Invalid month and day
console.log(invalidDate.isValid()); // false
console.log(invalidDate.invalidAt()); // 1 (month field index)

const invalidFormat = moment("not a date");
console.log(invalidFormat.isValid()); // false

// Strict parsing validation
const strictValid = moment("2023-12-25", "YYYY-MM-DD", true);
const strictInvalid = moment("25/12/2023", "YYYY-MM-DD", true);
console.log(strictValid.isValid()); // true
console.log(strictInvalid.isValid()); // false

// Parsing flags for debugging
const debugMoment = moment("2023-13-45");
const flags = debugMoment.parsingFlags();
console.log(flags.overflow); // 1 (month overflow)
console.log(flags.invalidMonth); // null
console.log(flags.parsedDateParts); // Array of parsed values

// Creation data
const createdMoment = moment("2023-12-25", "YYYY-MM-DD", "en", true);
const creation = createdMoment.creationData();
console.log(creation.input); // "2023-12-25"
console.log(creation.format); // "YYYY-MM-DD"
console.log(creation.strict); // true
console.log(creation.isUTC); // false

// Validation in conditional logic
function processDate(dateString) {
  const date = moment(dateString);
  
  if (!date.isValid()) {
    throw new Error(`Invalid date: ${dateString}`);
  }
  
  return date.format("YYYY-MM-DD");
}

// Working with potentially invalid input
const userInputs = ["2023-12-25", "invalid", "2023-02-30"];
const validDates = userInputs
  .map(input => moment(input))
  .filter(m => m.isValid())
  .map(m => m.format("YYYY-MM-DD"));

console.log(validDates); // ["2023-12-25"] (only valid dates)

Timezone and DST Validation

Methods for checking timezone and daylight saving time status.

/**
 * Check if this moment is in local time mode
 * @returns true if local time, false if UTC
 */
isLocal(): boolean;

/**
 * Check if this moment is in UTC mode
 * @returns true if UTC, false if local
 */
isUTC(): boolean;
isUtc(): boolean; // Alias

/**
 * Check if UTC offset has been explicitly set
 * @returns true if offset is set, false otherwise
 */
isUtcOffset(): boolean;

/**
 * Check if current time is during Daylight Saving Time
 * @returns true if in DST, false otherwise
 */
isDST(): boolean;

/**
 * Check if current year is a leap year
 * @returns true if leap year, false otherwise
 */
isLeapYear(): boolean;

Usage Examples:

import moment from "moment";

// Timezone mode checking
const localMoment = moment();
const utcMoment = moment.utc();
const offsetMoment = moment().utcOffset(300);

console.log(localMoment.isLocal()); // true
console.log(localMoment.isUTC()); // false

console.log(utcMoment.isLocal()); // false
console.log(utcMoment.isUTC()); // true

console.log(offsetMoment.isUtcOffset()); // true

// DST checking (depends on system timezone and date)
const summerDate = moment("2023-07-15"); // Likely DST
const winterDate = moment("2023-12-15"); // Likely standard time

console.log(summerDate.isDST()); // true (if in DST timezone)
console.log(winterDate.isDST()); // false

// Leap year checking
console.log(moment("2023-01-01").isLeapYear()); // false
console.log(moment("2024-01-01").isLeapYear()); // true (2024 is leap year)
console.log(moment("2000-01-01").isLeapYear()); // true
console.log(moment("1900-01-01").isLeapYear()); // false (not divisible by 400)

// Practical timezone validation
function ensureUTC(momentInstance) {
  if (!momentInstance.isUTC()) {
    return momentInstance.clone().utc();
  }
  return momentInstance;
}

function ensureLocal(momentInstance) {
  if (!momentInstance.isLocal()) {
    return momentInstance.clone().local();
  }
  return momentInstance;
}

Static Validation Methods

Static methods available on the moment object for type checking.

/**
 * Check if value is a Moment instance
 * @param m - Value to check
 * @returns true if value is a Moment instance
 */
function isMoment(m: any): m is Moment;

/**
 * Check if value is a native Date instance
 * @param m - Value to check  
 * @returns true if value is a Date instance
 */
function isDate(m: any): m is Date;

/**
 * Check if value is a Duration instance
 * @param d - Value to check
 * @returns true if value is a Duration instance
 */
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 stringObj = "2023-12-25";
const numberObj = 1640447400000;

// Type checking
console.log(moment.isMoment(momentObj)); // true
console.log(moment.isMoment(dateObj)); // false
console.log(moment.isMoment(stringObj)); // false

console.log(moment.isDate(dateObj)); // true
console.log(moment.isDate(momentObj)); // false
console.log(moment.isDate(stringObj)); // false

console.log(moment.isDuration(durationObj)); // true
console.log(moment.isDuration(momentObj)); // false
console.log(moment.isDuration(numberObj)); // false

// Practical usage in functions
function formatInput(input) {
  if (moment.isMoment(input)) {
    return input.format("YYYY-MM-DD");
  } else if (moment.isDate(input)) {
    return moment(input).format("YYYY-MM-DD");
  } else {
    return moment(input).format("YYYY-MM-DD");
  }
}

function safeDuration(input) {
  if (moment.isDuration(input)) {
    return input;
  } else {
    return moment.duration(input);
  }
}

// Type guards in TypeScript
function processMoment(input: unknown) {
  if (moment.isMoment(input)) {
    // TypeScript knows input is Moment here
    return input.format("YYYY-MM-DD");
  }
  
  if (moment.isDate(input)) {
    // TypeScript knows input is Date here
    return moment(input).format("YYYY-MM-DD");
  }
  
  throw new Error("Invalid input type");
}

docs

comparison-validation.md

creation-parsing.md

display-formatting.md

duration.md

getters-setters.md

index.md

locale.md

manipulation.md

utilities.md

tile.json