MomentJS - Parsing Date And Time
Modern Date/Time: Parsing with Moment.js
Section titled “Modern Date/Time: Parsing with Moment.js”Parsing is the process of taking raw input (like strings, objects, or arrays) and converting it into a structured date/time object that Moment.js can understand and manipulate. Moment.js offers flexible parsing capabilities.
As always, keep in mind Moment.js’s maintenance status when choosing tools for new development.
Creating Moment Objects (Parsing)
Section titled “Creating Moment Objects (Parsing)”The moment() function is the primary way to create Moment objects. It intelligently parses various input types:
| Input Type | Example & Notes |
|---|---|
| No Input (Now) | moment()Creates a Moment object representing the current date and time. |
| String (ISO 8601 & RFC 2822) | moment('2023-10-26T10:30:00')moment('Thu, 26 Oct 2023 10:30:00 GMT')Moment attempts to parse standard formats automatically. |
| String + Format | moment('26/10/2023', 'DD/MM/YYYY')Essential when the string format isn’t standard or is ambiguous. Tokens match those used in .format(). Highly recommended for reliability. |
| String + Multiple Formats | moment('26-Oct-2023', ['DD/MM/YYYY', 'DD-MMM-YYYY'])Moment tries formats in order until one matches. |
| Object | moment({ year: 2023, month: 9, day: 26, hour: 10, minute: 30 })Keys correspond to date/time units. Month is 0-indexed (0 = January, 9 = October). Unspecified units default to the lowest possible value (e.g., 0 for hour/minute/second). |
| Native Date Object | moment(new Date(2023, 9, 26))Creates a Moment object from a standard JavaScript Date. Remember the native Date month is also 0-indexed. |
| Array | moment([2023, 9, 26, 10, 30, 0])Mirrors arguments for new Date(): [year, month, day, hour, minute, second, millisecond]. Month is 0-indexed. |
| Unix Timestamp (Milliseconds) | moment(1698316200000)Parses milliseconds since the Unix Epoch (Jan 1, 1970 UTC). |
| Unix Timestamp (Seconds) | moment.unix(1698316200)Use moment.unix() for seconds since the Unix Epoch. |
| Cloning a Moment Object | const original = moment();const clone = moment(original); or const clone = original.clone();Creates a new independent Moment object with the same date/time value. Crucial for avoiding unintended modification of original moments (see ‘Manipulation’ section). |
| UTC Mode | moment.utc()moment.utc('2023-10-26')moment.utc([2023, 9, 26])Parses the input as UTC, ignoring the local timezone. |
| Parse Zone | moment.parseZone('2023-10-26T10:30:00+02:00')Parses the string and preserves the included timezone offset, rather than converting to local or UTC. |
| Strict Parsing | moment('26/10/2023', 'DD/MM/YYYY', true); // Strict modemoment('26/10/XYZ', 'DD/MM/YYYY', true).isValid(); // falseRequires the input to strictly match the format string (no lenient parsing). |
| Locale-aware Parsing | moment('26 octobre 2023', 'D MMMM YYYY', 'fr');Parses using the specified locale’s month/weekday names. |
Inspecting Creation Data
Section titled “Inspecting Creation Data”Sometimes it’s useful to see how Moment parsed the input, especially for debugging invalid dates:
const m = moment('2023/10/26', 'DD/MM/YYYY');console.log(m.creationData());
/* Example Output:{ input: '2023/10/26', format: 'DD/MM/YYYY', locale: Locale {_abbr: 'en', ...}, isUTC: false, strict: false}*/This object contains details about the input string, format used, locale, and parsing flags. See the ‘Validation’ section for more on flags like overflow, invalidMonth etc.
Best Practices
Section titled “Best Practices”- Always Specify Format: When parsing strings other than strict ISO 8601, always provide the format string (
moment(inputString, formatString)) to avoid ambiguity and parsing errors. - Use Strict Parsing: Consider enabling strict parsing (
trueas the third argument) for critical inputs to ensure data integrity. - Beware 0-Indexed Months: Remember that months are 0-indexed (Jan=0, Dec=11) when parsing from Objects or Arrays.
Detailed parsing options can be found in the official documentation: https://momentjs.com/docs/#/parsing/