Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
February 26, 2021 10:12 am GMT

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') // ISOd = dayjs(1318781876406) // Javascript timestamps -- Millisd = dayjs.unix(1318781876) // Unix timestampsd = new Date(2018, 8, 18) // Date objectd = 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


Original Link: https://dev.to/javidjms/dayjs-awesome-lightweight-modern-date-api-and-an-alternative-to-momentjs-49lf

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To