DEV Community

Cover image for DayJS: Awesome lightweight modern Date API and an alternative to MomentJS
Javid Mougamadou
Javid Mougamadou

Posted on

DayJS: Awesome lightweight modern Date API and an alternative to MomentJS

Concepts

DayJS is a lightweight JavaScript date API (2kB) which describe the same MomentJS API. (If you use Moment.js so could use easily Day.js )

Day.js is a minimalist and simple library that parses, validates, manipulates, and displays dates and times for modern browsers.

Why DayJS replace Momentjs

Image

Image

Tree-shaking: Moment doesn't work well with modern "tree shaking" algorithms, so it tends to increase the size of web application bundles.

Mutable: consider that Moment objects are mutable. Changing Moment to be immutable would be a breaking change for every one of the projects that use it.

Get Started

Installation

npm install dayjs
Enter fullscreen mode Exit fullscreen mode
import dayjs from 'dayjs' // ES 2015
Enter fullscreen mode Exit fullscreen mode

Parse

now = dayjs();
d = dayjs('2013-03-01', 'YYYY-MM-DD');
d = dayjs('2018-04-04T16:00:00.000Z') // ISO
d = dayjs(1318781876406) // Javascript timestamps -- Millis
d = dayjs.unix(1318781876) // Unix timestamps
d = new Date(2018, 8, 18) // Date object
d = dayjs({ years:2010, months:3, date:5, hours:15, minutes:10, seconds:3, milliseconds:123});
Enter fullscreen mode Exit fullscreen mode

Format

d.format()            // "2013-03-01T00:00:00+01:00"
d.format('dddd')      // "Friday"
d.format('MMM Do YY') // "Mar 1st 13"
d.fromNow()           // "7 years ago"
d.calendar()          // "03/01/2013"
Enter fullscreen mode Exit fullscreen mode

Get/Set

dayjs().second() // => new Date().getSeconds()
dayjs().second(30).valueOf() // => new Date().setSeconds(30)

dayjs().hour()
dayjs().hour(12)
Enter fullscreen mode Exit fullscreen mode

Manipulate (Add-Substract)

d.add(1, 'day')
d.subtract(2, 'days')
d.startOf('day')
d.endOf('day')
d.startOf('hour')
Enter fullscreen mode Exit fullscreen mode

Query

d.isBefore(dayjs('2011-01-01'))
d.isSame(dayjs('2011-01-01'))
d.isAfter(dayjs('2011-01-01'))
Enter fullscreen mode Exit fullscreen mode

Bundlephobia

Alt Text

Alt Text

Link

Top comments (6)

Collapse
 
alaindet profile image
Alain D'Ettorre

I've used dayjs in an Angular project to create a custom datepicker. It was not a very good experience honestly. I'll try date-fns or luxon next time

Collapse
 
mrtung profile image
Mr TΓΉng

Agree. I using date-fns for my big project, it's awesome.

Collapse
 
zynth17 profile image
Christopher Reeve

i use date-fns
dayjs is only good in the size but not the performance

Collapse
 
andrewbaisden profile image
Andrew Baisden

Now this is a good library to use.

Collapse
 
lyrod profile image
Lyrod

I used date-fns but dayjs looks awesome!

Collapse
 
ibrahimcesar profile image
Ibrahim Cesar

This is my go-to date library