Parse, validate, manipulate, and display dates and times in JavaScript with internationalization support
npx @tessl/cli install tessl/npm-moment@2.30.0Moment.js is a comprehensive JavaScript library for parsing, validating, manipulating, and formatting dates and times. It provides a rich API with over 100 locales, flexible parsing from various date formats, intuitive methods for date arithmetic, and powerful formatting capabilities.
Note: Moment.js is now in maintenance mode with the project status indicating it's a legacy library. New projects should consider alternatives like Day.js, date-fns, or Luxon.
npm install momentES6 Modules:
import moment from "moment";
// or
import * as moment from "moment";CommonJS:
const moment = require("moment");Browser (Global):
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.30.1/moment.min.js"></script>
<script>
// moment is available globally
</script>import moment from "moment";
// Create moments
const now = moment(); // Current date/time
const birthday = moment("1990-06-15"); // Parse date string
const specific = moment("2023-12-25 15:30", "YYYY-MM-DD HH:mm"); // With format
// Display
console.log(now.format()); // ISO 8601 string
console.log(birthday.format("MMMM Do, YYYY")); // "June 15th, 1990"
console.log(specific.fromNow()); // "2 months ago" (relative)
// Manipulate
const nextWeek = moment().add(7, "days");
const startOfDay = moment().startOf("day");
const endOfMonth = moment().endOf("month");
// Validate and compare
console.log(moment("invalid").isValid()); // false
console.log(birthday.isBefore(now)); // true
console.log(nextWeek.diff(now, "days")); // 7Moment.js is built around several key components:
moment() function with multiple parsing modes and format supportCore functionality for creating Moment instances from various input types including strings, dates, numbers, and arrays with flexible parsing options.
// Main constructor (overloaded)
function moment(inp?: MomentInput, strict?: boolean): Moment;
function moment(inp?: MomentInput, format?: MomentFormatSpecification, strict?: boolean): Moment;
function moment(inp?: MomentInput, format?: MomentFormatSpecification, language?: string, strict?: boolean): Moment;
// UTC constructor
function utc(inp?: MomentInput, strict?: boolean): Moment;
function utc(inp?: MomentInput, format?: MomentFormatSpecification, strict?: boolean): Moment;
function utc(inp?: MomentInput, format?: MomentFormatSpecification, language?: string, strict?: boolean): Moment;
// Unix timestamp constructor
function unix(timestamp: number): Moment;
// Timezone-aware parsing
function parseZone(inp?: MomentInput, format?: MomentFormatSpecification, strict?: boolean): Moment;
function parseZone(inp?: MomentInput, format?: MomentFormatSpecification, language?: string, strict?: boolean): Moment;Comprehensive formatting system with customizable format strings, relative time display, calendar formatting, and localized output.
// Formatting methods on Moment instances
format(format?: string): string;
toString(): string;
toISOString(keepOffset?: boolean): string;
toJSON(): string;
// Relative time formatting
fromNow(withoutSuffix?: boolean): string;
toNow(withoutPrefix?: boolean): string;
from(inp: MomentInput, suffix?: boolean): string;
to(inp: MomentInput, suffix?: boolean): string;
// Calendar formatting
calendar(): string;
calendar(formats: CalendarSpec): string;
calendar(time: MomentInput, formats?: CalendarSpec): string;Date manipulation methods for adding/subtracting time, setting specific values, and navigating to specific time boundaries.
// Arithmetic operations
add(amount?: DurationInputArg1, unit?: DurationInputArg2): Moment;
subtract(amount?: DurationInputArg1, unit?: DurationInputArg2): Moment;
// Boundary operations
startOf(unitOfTime: unitOfTime.StartOf): Moment;
endOf(unitOfTime: unitOfTime.StartOf): Moment;
// Timezone manipulation
local(keepLocalTime?: boolean): Moment;
utc(keepLocalTime?: boolean): Moment;
utcOffset(): number;
utcOffset(b: number|string, keepLocalTime?: boolean): Moment;Dual-purpose methods for reading and writing specific date/time components with support for all time units.
// Dual-purpose getter/setter methods
year(): number;
year(y: number): Moment;
month(): number;
month(M: number|string): Moment;
date(): number;
date(d: number): Moment;
hour(): number;
hour(h: number): Moment;
minute(): number;
minute(m: number): Moment;
second(): number;
second(s: number): Moment;
// Generic getter/setter
get(unit: unitOfTime.All): number;
set(unit: unitOfTime.All, value: number): Moment;
set(objectLiteral: MomentSetObject): Moment;Methods for comparing Moment instances, validating dates, and determining relationships between different time points.
// Comparison methods
isBefore(inp?: MomentInput, granularity?: unitOfTime.StartOf): boolean;
isAfter(inp?: MomentInput, granularity?: unitOfTime.StartOf): boolean;
isSame(inp?: MomentInput, granularity?: unitOfTime.StartOf): boolean;
isSameOrAfter(inp?: MomentInput, granularity?: unitOfTime.StartOf): boolean;
isSameOrBefore(inp?: MomentInput, granularity?: unitOfTime.StartOf): boolean;
isBetween(a: MomentInput, b: MomentInput, granularity?: unitOfTime.StartOf, inclusivity?: "()" | "[)" | "(]" | "[]"): boolean;
// Difference calculation
diff(b: MomentInput, unitOfTime?: unitOfTime.Diff, precise?: boolean): number;
// Validation
isValid(): boolean;
invalidAt(): number;Complete duration system for working with time intervals, performing duration arithmetic, and formatting duration output.
// Duration constructor
function duration(inp?: DurationInputArg1, unit?: DurationInputArg2): Duration;
// Duration interface methods
interface Duration {
clone(): Duration;
humanize(argWithSuffix?: boolean, argThresholds?: argThresholdOpts): string;
abs(): Duration;
as(units: unitOfTime.Base): number;
get(units: unitOfTime.Base): number;
add(inp?: DurationInputArg1, unit?: DurationInputArg2): Duration;
subtract(inp?: DurationInputArg1, unit?: DurationInputArg2): Duration;
toISOString(): string;
isValid(): boolean;
}Comprehensive internationalization system with support for 100+ locales, custom locale definitions, and locale-aware formatting.
// Global locale management
function locale(language?: string): string;
function locale(language?: string[], definition?: LocaleSpecification): string;
function defineLocale(language: string, localeSpec: LocaleSpecification): Locale;
function updateLocale(language: string, localeSpec: LocaleSpecification): Locale;
function locales(): string[];
// Instance locale methods
locale(): string;
locale(locale: LocaleSpecifier): Moment;
localeData(): Locale;
// Display name functions
function months(): string[];
function monthsShort(): string[];
function weekdays(): string[];
function weekdaysShort(): string[];
function weekdaysMin(): string[];Locale and Internationalization
Static utility functions for type checking, min/max operations, normalization, and global configuration.
// Type checking
function isMoment(m: any): m is Moment;
function isDate(m: any): m is Date;
function isDuration(d: any): d is Duration;
// Min/max operations
function min(moments: Moment[]): Moment;
function max(moments: Moment[]): Moment;
// Utility functions
function now(): number;
function invalid(flags?: MomentParsingFlagsOpt): Moment;
function normalizeUnits(unit: unitOfTime.All): string;
// Configuration
function relativeTimeThreshold(threshold: string): number | boolean;
function relativeTimeThreshold(threshold: string, limit: number): boolean;
function relativeTimeRounding(fn: (num: number) => number): boolean;// Main interfaces
interface Moment {
// Full interface definition available in sub-docs
}
interface Duration {
// Full interface definition available in sub-docs
}
interface Locale {
// Full interface definition available in sub-docs
}
// Input types
type MomentInput = Moment | Date | string | number | (number | string)[] | MomentInputObject | void;
type LocaleSpecifier = string | Moment | Duration | string[] | boolean;
type MomentFormatSpecification = string | MomentBuiltinFormat | (string | MomentBuiltinFormat)[];
// Utility types
type numberlike = number | string;
type MomentBuiltinFormat = string;
// Configuration objects
interface MomentInputObject {
years?: numberlike;
months?: numberlike;
days?: numberlike;
hours?: numberlike;
minutes?: numberlike;
seconds?: numberlike;
milliseconds?: numberlike;
}
interface MomentSetObject extends MomentInputObject {
quarters?: numberlike;
weeks?: numberlike;
weekYear?: numberlike;
isoWeekYear?: numberlike;
dayOfYear?: numberlike;
weekday?: numberlike;
isoWeekday?: numberlike;
}// Version information
const version: string; // "2.30.1"
// Built-in format constants
const ISO_8601: MomentBuiltinFormat;
const RFC_2822: MomentBuiltinFormat;
// HTML5 input formats
const HTML5_FMT: {
DATETIME_LOCAL: string; // "YYYY-MM-DDTHH:mm"
DATETIME_LOCAL_SECONDS: string; // "YYYY-MM-DDTHH:mm:ss"
DATETIME_LOCAL_MS: string; // "YYYY-MM-DDTHH:mm:ss.SSS"
DATE: string; // "YYYY-MM-DD"
TIME: string; // "HH:mm"
TIME_SECONDS: string; // "HH:mm:ss"
TIME_MS: string; // "HH:mm:ss.SSS"
WEEK: string; // "GGGG-[W]WW"
MONTH: string; // "YYYY-MM"
};
// Configuration
let defaultFormat: string;
let defaultFormatUtc: string;
let suppressDeprecationWarnings: boolean;
let deprecationHandler: ((name: string | void, msg: string) => void) | void;