Explain Codes LogoExplain Codes Logo

Parsing a string to a date in JavaScript

javascript
date-parsing
momentjs
regex
Alex KataevbyAlex Kataev·Aug 10, 2024
TLDR

You can transform a date string to a Date object in a snap with JavaScript's new Date() or Date.parse() for ISO strings. For custom formats, consider using moment.js for consistency.

// It's like magic but for ISO date string const isoDate = new Date('2022-12-25'); // Night harnessing the power of moment.js for non-standard format const customDate = moment('25/12/2022', 'DD/MM/YYYY').toDate();

Fair warning: Native JavaScript parsing may vary across browsers; libraries like moment.js help ensure consistent behavior.

Displaying dates in UTC and local time

Handling dates exquisitely in UTC

For world-facing applications, be kind to yourself and store and compute dates in UTC to sidestep pesky timezone issues. You can get an ISO date string to interpret as UTC simply by slapping on a 'Z'.

// Z stands for Zulu, and Zulu time is UTC. Neat, huh? const dateUTC = new Date('2022-12-25T00:00:00Z'); console.log(dateUTC.toUTCString()); // Will dispense the date in UTC

Parading dates in local time

We humans like things local, including time. Just invoke .toString() on a Date object for the local flavor.

// Spice it up with some human friendly, local seasoning const dateLocal = new Date('2022-12-25T00:00:00Z'); console.log(dateLocal.toString()); // Brings you the date in local time

Tender loving care for Internet Explorer

Even good ol' Internet Explorer gets some love. Bypass parsing inconsistencies by splitting the date string.

// IE celebration code right here var dateParts = '2022-12-25'.split('-'); var year = parseInt(dateParts[0], 10); var month = parseInt(dateParts[1], 10) - 1; // Adjust for 0-based index var day = parseInt(dateParts[2], 10); // All split and ready to go var dateIE = new Date(year, month, day);

Delving into date parsing libraries

Moment.js in the spotlight

Date objects are great, but when it comes to parsing and formatting like a pro, moment.js merits applause:

// Get comfortable, let moment.js do the heavy lifting const dateStr = '25/12/2022 12:34:56 PM'; const dateWithTimezone = moment.tz(dateStr, "DD/MM/YYYY hh:mm:ss A", "Europe/London").toDate();

Modern masters taking the stage

Starring date-fns and day.js as agreeable, lightweight understudies to moment.js.

// date-fns: Small, but mighty! import { parse } from 'date-fns'; // 'dd.MM.yyyy': Nice and tidy custom format for date-fns const customFormat = 'dd.MM.yyyy'; const dateFnsDate = parse('25.12.2022', customFormat, new Date());

The art of parsing custom date formats

Parsing with regex: do the twist

Flex the might of regular expressions to erleap from string to date object:

// A regex twist with some date string salsa, served by JavaScript const dateString = '25.12.2022'; const regex = /^(\d{2})\.(\d{2})\.(\d{4})$/; const [, day, month, year] = dateString.match(regex); const dateFromRegex = new Date(year, month - 1, day);

Manual parsing: the olden gold

There are times when automation amiss; manual parsing yields golden control:

function parseDate(dateStr) { const parts = dateStr.split('/'); const day = parseInt(parts[0], 10); const month = parseInt(parts[1], 10) - 1; // Brace yourself, JavaScript months start at 0 const year = parseInt(parts[2], 10); return new Date(year, month, day); }

Time zone tangle

Untreated strings may default to local time, inviting peculiar results. Always inject clarity of time zone:

const ambiguousDate = new Date('2022-12-25'); // Local? UTC? Who knows! const explicitDate = new Date('2022-12-25T00:00:00Z'); // Clearly UTC

Fumbling with fakeries

JavaScript's parsing of invalid dates cunningly avoids error throw and returns Invalid Date instead. Stay alert:

const invalidDate = new Date('not-a-date'); if (isNaN(invalidDate)) { console.error('That date isn\'t a date at all!'); // Oops! }

Leap years leap out

While built-in parsers might stumble, manual parsing can gracefully waltz with leap years and other calendar oddities:

if ((year % 4 === 0 && year % 100 !== 0) || year % 400 === 0) { // 'Cause leap year likes to jump in every now and then! }