Tutorial

Parse, Validate, Manipulate, and Display Dates and Times in JavaScript with Day.js

Published on December 28, 2019
Default avatar

By joshtronic

Parse, Validate, Manipulate, and Display Dates and Times in JavaScript with Day.js

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

With it’s last release nearly a year ago, the most recent commit over 6 months ago, and hundreds of open bugs and pull requests, it’s starting to seem like Moment.js is slowing down and it’s time to shop for more actively maintained alternatives. Insert Day.js, a minimalist date and time library weighing in at 2kB that provides a mostly Moment.js-compatible API for ease of transition.

Getting Started with Day.js

To get started with Day.js in your Node.js project, simply add the dependency with either npm or yarn:

$ npm install dayjs --save
# or
$ yarn add dayjs

Then simply include it in your script:

const dayjs = require('dayjs');

Day.js also works in modern browsers and can be self-hosted or included by way of a CDN provider like cdnjs.

Parsing Dates and Times

Parsing a date and time string into a Day.js object is easy and supports strings, numbers, native JavaScript Date objects as well as other Day.js objects:

let date = dayjs('2019-12-27');
date = dayjs('20191227');
date = dayjs(new Date(2019, 11, 27));
date = dayjs(day('2019-12-27'));

You can even omit the string entirely to default the Day.js object to the current date and time:

date = dayjs();

Validating Dates and Times

Once you’ve parsed a date and time with Day.js you can leverage the isValid() method to determine if what you passed in was actually something Day.js could parse:

dayjs('2019-12-27').isValid(); // true
dayjs('tomorrow').isValid(); // false

Additionally, if you were to attempt to display a Day.js object that was fed with a date that couldn’t be parsed, the return will be Invalid Date.

Displaying Dates and Times

The .format() method allows us to take the Day.js object and convert it into a human-readable string. It supports your common set of date and time variables, like YYYY for a full year, and MM and mm for month and minutes respectively.

For those times when you want to include additional text that you don’t want to be converted to a date or time part, you can “hug” the string with brackets [ and ]:

dayjs().format('YYYY-MM-DD [at] HH:mm:ss');
dayjs().format('HH:mm:ss [on] YYYY-MM-DD');

Manipulating Dates and Times

In a previous section we attempted to pass in the string tomorrow and it was considered an invalid date. To be able to get the date and time for tomorrow, we can start with today’s date and time, and add a day to it:

dayjs().add(1, 'day').format('YYYY-MM-DD');

In addition to adding a day, you can also add month and year and even time-based intervals like hour and minute:

dayjs().add(1, 'hour').format('YYYY-MM-DD HH:mm:ss');
dayjs().add(30, 'minute').format('YYYY-MM-DD HH:mm:ss');
dayjs().add(3, 'month').format('YYYY-MM-DD HH:mm:ss');
dayjs().add(3, 'year').format('YYYY-MM-DD HH:mm:ss');

You can even chain it to do things like add multiple intervals:

dayjs().add(1, 'hour').add(30, 'minute').format('YYYY-MM-DD HH:mm:ss');

Don’t you worry, there’s a subtraction method as well:

dayjs().subtract(4, 'hour').format('YYYY-MM-DD HH:mm:ss');

Comparing Dates and Times

One of the more complex tasks that comes up pretty regularly in development is the comparison of dates and times. Day.js makes it easy be providing helper methods such as isBefore() and isAfter():

const date1 = dayjs('2020-01-1');
const date2 = dayjs();

if (date1.isBefore(date2)) {
  console.log('Date 1 falls before date 2');
}
else if (date1.isAfter(date2)) {
  console.log('Date 2 falls before date 1');
}
else if (date1.isSame(date2)) {
  console.log('Date 1 and date 2 are the same');
}

Conclusion

With it’s familiar interfacing and active maintenance (even during the holidays), Day.js seems like a great alternative for Moment.js.

Give it a try on your next project, I know I will be.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about us


About the authors
Default avatar
joshtronic

author

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
Leave a comment


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Get our biweekly newsletter

Sign up for Infrastructure as a Newsletter.

Hollie's Hub for Good

Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

Become a contributor

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

Welcome to the developer cloud

DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

Learn more
DigitalOcean Cloud Control Panel