JavaScript Date VS Moment.js

Purpose Image
The Power of Purpose: How Meaningful Work Leads to Happiness
9th October 2024
React JS
Unique Features of React.js: Why It’s a Game Changer for Web Development
15th October 2024
Purpose Image
The Power of Purpose: How Meaningful Work Leads to Happiness
9th October 2024
React JS
Unique Features of React.js: Why It’s a Game Changer for Web Development
15th October 2024

How to Create a Date Object

Get the current date and time

const now = new Date();

// Mon Aug 10 2019 12:58:21 GMT-0400 (Eastern Daylight Time)

Get a date and time with individual values

const specifiedDate = new Date(2019, 4, 29, 15, 0, 0, 0);

// Wed May 29 2019 15:00:00 GMT-0400 (Eastern Daylight Time)

The syntax is Date(year, month, day, hour, minute, second, millisecond).

Note that the months are zero-indexed, beginning with January at 0 and ending with December at 11.

Get a date and time from a timestamp

const unixEpoch = new Date(0);

This represents the time at Thursday, January 1st, 1970 (UTC), or the Unix Epoch time. The Unix Epoch is important because it’s what JavaScript, Python, PHP, and other languages and systems use internally to calculate the current time.

new Date(ms) returns the date of the epoch plus the number of milliseconds you pass in. In a day there’s 86,400,000 milliseconds so:

const dayAfterEpoch = new Date(86400000);

will return Friday, January 2nd, 1970 (UTC).

Get a date and time from a string

const stringDate = new Date('May 29, 2019 15:00:00');

// Wed May 29 2019 15:00:00 GMT-0400 (Eastern Daylight Time)

Setting a time zone

When passing a date string without setting a time zone, JavaScript assumes the date/time are in UTC before converting it to your browser’s time zone:
const exactBirthdate = new Date('6/13/2018 06:27:00');

console.log(exactBirthdate) // Wed Jun 13 2018 06:27:00 GMT+0900 (Korean Standard Time)

This can lead to errors where the date returned is off by many hours. To avoid this, pass in a time zone along with the string:

const exactBirthdate = new Date('6/13/2018 06:27:00 GMT-1000');

console.log(exactBirthdate) // Thu Jun 14 2018 01:27:00 GMT+0900 (Korean Standard Time)

/*
These formats also work:

new Date('6/13/2018 06:27:00 GMT-10:00');
new Date('6/13/2018 06:27:00 -1000');
new Date('6/13/2018 06:27:00 -10:00');
*/
You can also pass some, but not all, time zone codes:
const exactBirthdate = new Date('6/13/2018 06:27:00 PDT');
console.log(exactBirthdate) // Thu Jun 14 2018 01:27:00 GMT+0900 (Korean Standard Time)

Date Object Methods

Often you will not need the entire date, but just part of it like the day, week or month. Fortunately there are a number of methods to do just that:
const birthday = new Date('6/13/2018 06:27:39');

birthday.getMonth() // 5 (0 is January)
birthday.getDate() // 13
birthday.getDay() // 3 (0 is Sunday)
birthday.getFullYear() // 2018
birthday.getTime() // 1528838859000 (milliseconds since the Unix Epoch)
birthday.getHours() // 6
birthday.getMinutes() // 27
birthday.getSeconds() // 39
birthday.getTimezoneOffset() // -540 (time zone offset in minutes based on your browser's location)

Make Working with Dates Easier with Moment.js

Getting dates and times right is no small task. Every country seems to have a different way of formatting dates, and accounting for different time zones and daylight savings/summer time takes, well, a whole lot of time. That’s where Moment.js shines – it makes parsing, formatting, and displaying dates a breeze.

To start using Moment.js, install it through a package manager like npm, or add it to your site through a CDN. See the Moment.js documentation for more details.

Get the current date and time with Moment.js

const now = moment();

This returns an object with the date and time based on your browser’s location, along with other locale information. It’s similar to native JavaScript’s new Date().

Get a date and time from a timestamp with Moment.js

Similar to new Date(ms), you can pass the number of milliseconds since the epoch to moment():

const dayAfterEpoch = moment(86400000);

If you want to get a date using a Unix timestamp in seconds, you can use the unix() method:

const dayAfterEpoch = moment.unix(86400);

Get a date and time from a string with Moment.js

Parsing a date from a string with Moment.js is easy, and the library accepts strings in the ISO 8601 or RFC 2822 Date Time format, along with any string accepted by the JavaScript Date object.

ISO 8601 strings are recommended since it is a widely accepted format. Here are some examples:
moment('2019-04-21');
moment('2019-04-21T05:30');
moment('2019-04-21 05:30');

moment('20190421');
moment('20190421T0530');

Setting a time zone with Moment.js

Up until now, we have been using Moment.js in local mode, meaning that any input is assumed to be a local date or time. This is similar to how the native JavaScript Date object works:
const exactBirthMoment = moment('2018-06-13 06:27:00');

console.log(exactBirthMoment) // Wed Jun 13 2018 06:27:00 GMT+0900 (Korean Standard Time)
However, to set a time zone, you must first get the Moment object in UTC mode:
const exactBirthMoment = moment.utc('2018-06-13 06:27:00');
console.log(exactBirthMoment) // Wed Jun 13 2018 15:27:00 GMT+0900 (Korean Standard Time)
Then you can adjust for the difference in time zones with the utcOffset() method:
const exactBirthMoment = moment.utc('2018-06-13 06:27:00').utcOffset('+10:00');
console.log(exactBirthMoment) // Wed Jun 13 2018 06:27:00 GMT+0900 (Korean Standard Time)

You can also set the UTC offset as a number or a string:

moment.utc().utcOffset(10) // Number of hours offset
moment.utc().utcOffset(600) // Number of minutes offset
moment.utc().utcOffset('+10:00') // Number of hours offset as a string

To use named time zones (America/Los_Angeles) or time zone codes (PDT) with Moment objects, check out the Moment Timezone library.

Format the date and time with Moment.js

One of the major strengths that Moment.js has over native JavaScript Date objects is how easy it is to format the output date and time. Just chain the format() method to a Moment date object and pass it a format string as a parameter:
moment().format('MM-DD-YY'); // "08-13-19"
moment().format('MM-DD-YYYY'); // "08-13-2019"
moment().format('MM/DD/YYYY'); // "08/13/2019"
moment().format('MMM Do, YYYY') // "Aug 13th, 2019"
moment().format('ddd MMMM Do, YYYY HH:mm:ss') // "Tues August 13th, 2019 19:29:20"
moment().format('dddd, MMMM Do, YYYY -- hh:mm:ss A') // "Tuesday, August 13th, 2019 -- 07:31:02 PM"

Similar blog:
Mongoose Vs MongoDB

For More Info: XpertLab.com