⏰ Day.js 2kB immutable date-time library alternative to Moment.js with the same modern API

Overview

English | 简体中文 | 日本語 | Português Brasileiro | 한국어 | Español (España) | Русский

Day.js

Fast 2kB alternative to Moment.js with the same modern API

Gzip Size NPM Version Build Status Codecov License
Sauce Test Status

Day.js is a minimalist JavaScript library that parses, validates, manipulates, and displays dates and times for modern browsers with a largely Moment.js-compatible API. If you use Moment.js, you already know how to use Day.js.

dayjs().startOf('month').add(1, 'day').set('year', 2018).format('YYYY-MM-DD HH:mm:ss');
  • 🕒 Familiar Moment.js API & patterns
  • 💪 Immutable
  • 🔥 Chainable
  • 🌐 I18n support
  • 📦 2kb mini library
  • 👫 All browsers supported

Getting Started

Documentation

You can find for more details, API, and other docs on day.js.org website.

Installation

npm install dayjs --save

📚 Installation Guide

API

It's easy to use Day.js APIs to parse, validate, manipulate, and display dates and times.

dayjs('2018-08-08') // parse

dayjs().format('{YYYY} MM-DDTHH:mm:ss SSS [Z] A') // display

dayjs().set('month', 3).month() // get & set

dayjs().add(1, 'year') // manipulate

dayjs().isBefore(dayjs()) // query

📚 API Reference

I18n

Day.js has great support for internationalization.

But none of them will be included in your build unless you use it.

import 'dayjs/locale/es' // load on demand

dayjs.locale('es') // use Spanish locale globally

dayjs('2018-05-05').locale('zh-cn').format() // use Chinese Simplified locale in a specific instance

📚 Internationalization

Plugin

A plugin is an independent module that can be added to Day.js to extend functionality or add new features.

import advancedFormat from 'dayjs/plugin/advancedFormat' // load on demand

dayjs.extend(advancedFormat) // use plugin

dayjs().format('Q Do k kk X x') // more available formats

📚 Plugin List

Sponsors

Support this project by becoming a sponsor. Your logo will show up here with a link to your website. [Become a sponsor]

Contributors

This project exists thanks to all the people who contribute.

Please give us a 💖 star 💖 to support us. Thank you.

And thank you to all our backers! 🙏

License

Day.js is licensed under a MIT License.

Comments
  • Add plugins methods to typescript definition

    Add plugins methods to typescript definition

    Should plugins's api methods be added in the core d.ts file? Or they should have their owns?

    If they have their own, they should be merge into one when bundling the package?

    I'm trying to use this library at another library, which is written with Typescript, and trying to use plugin methods, it's driving me crazy. Any thoughts?

    discussion 
    opened by naulacambra 41
  • Localisation issues in `sk.js` (Slovak)

    Localisation issues in `sk.js` (Slovak)

    Related #302 #4


    There are some issues in sk.js:

    • ordinal: n => `${n}º`,ordinal: n => `${n}.`,:
      • there should a dot after ordinal numbers;
    • L: 'DD.MM.YYYY',L: 'DD. MM. YYYY',:
      • according to STN 01 6910 (in Slovak), the spaces after each dot in the date is prefered, but the spaces can be omitted, therefore this is not an issue per se;
    • weekdays: 'Nedeľa_Pondelok_Utorok_Streda_Štvrtok_Piatok_Sobota'.split('_'),weekdays: 'nedeľa_pondelok_utorok_streda_štvrtok_piatok_sobota'.split('_'),
    • weekdaysShort: 'Ne_Po_Ut_St_Št_Pi_So'.split('_'),weekdaysShort: 'ne_po_ut_st_št_pi_so'.split('_'),.

    Then there is as an issue with the the numbers of and declension of the nouns (see also #302). The grammatical rules in Slovak are quite similar to those in Czech, therefore I have just copied the plural() and translate() functions from there and replaced the nouns with the Slovak ones. I would open a PR with this, but I am not a good coder, therefore this must be reviewed.

    All in all, here is the proposed content of sk.js. I hope I did not made any mistakes. I have added some comments to make it easier to check if the words are really those that should be assigned to the particular key.

    sk.js
    // Slovak [sk]
    import dayjs from 'dayjs'
    
    function plural(n) {
      return (n > 1) && (n < 5) && (~~(n / 10) !== 1) // eslint-disable-line
    }
    
    /* eslint-disable */ 
    function translate(number, withoutSuffix, key, isFuture) {
      const result = `${number} `
      switch (key) {
        case 's': // a few seconds / in a few seconds / a few seconds ago
          // in a few seconds / a few seconds ago
          return (withoutSuffix || isFuture) ? 'pár sekúnd' : 'pár sekundami'
        case 'm': // a minute / in a minute / a minute ago
          return withoutSuffix ? 'minúta' : (isFuture ? 'minútu' : 'minútou')
        case 'mm': // 9 minutes / in 9 minutes / 9 minutes ago
          if (withoutSuffix || isFuture) {
            // 2-4 minutes / 5+ minutes
            return result + (plural(number) ? 'minúty' : 'minút')
          }
          // 2+ minutes ago
          return `${result}minútami`
        case 'h': // an hour / in an hour / an hour ago
          return withoutSuffix ? 'hodina' : (isFuture ? 'hodinu' : 'hodinou')
        case 'hh': // 9 hours / in 9 hours / 9 hours ago
          if (withoutSuffix || isFuture) {
            // 2-4 hours / 5+ hours
            return result + (plural(number) ? 'hodiny' : 'hodín')
          }
          // 2+ hours ago
          return `${result}hodinami`
        case 'd': // a day / in a day / a day ago
          // in a day / a day ago
          return (withoutSuffix || isFuture) ? 'deň' : 'dňom'
        case 'dd': // 9 days / in 9 days / 9 days ago
          if (withoutSuffix || isFuture) {
            // 2-4 days / 5+ days
            return result + (plural(number) ? 'dni' : 'dní')
          }
          // 2+ days ago
          return `${result}dny`
        case 'M': // a month / in a month / a month ago
          // in a month / a month ago
          return (withoutSuffix || isFuture) ? 'mesiac' : 'mesiacom'
        case 'MM': // 9 months / in 9 months / 9 months ago
          if (withoutSuffix || isFuture) {
            // 2-4 months / 5+ months
            return result + (plural(number) ? 'mesiace' : 'mesiacov')
          }
          // 2+ months ago
          return `${result}mesiacmi`
        case 'y': // a year / in a year / a year ago
          // in a year / a year ago
          return (withoutSuffix || isFuture) ? 'rok' : 'rokom'
        case 'yy': // 9 years / in 9 years / 9 years ago
          if (withoutSuffix || isFuture) {
            // 2-4 years / 5+ years
            return result + (plural(number) ? 'roky' : 'rokov')
          }
          // 2+ year ago
          return `${result}rokmi`
      }
    }
    /* eslint-enable */
    
    const locale = {
      name: 'sk',
      weekdays: 'nedeľa_pondelok_utorok_streda_štvrtok_piatok_sobota'.split('_'),
      weekdaysShort: 'ne_po_ut_st_št_pi_so'.split('_'),
      weekdaysMin: 'ne_po_ut_st_št_pi_so'.split('_'),
      months: 'január_február_marec_apríl_máj_jún_júl_august_september_október_november_december'.split('_'),
      monthsShort: 'jan_feb_mar_apr_máj_jún_júl_aug_sep_okt_nov_dec'.split('_'),
      weekStart: 1,
      relativeTime: {
        future: 'o %s',
        past: 'pred %s',
        s: 'niekoľko sekúnd',
        m: 'minúta',
        mm: '%d minút',
        h: 'hodina',
        hh: '%d hodín',
        d: 'deň',
        dd: '%d dní',
        M: 'mesiac',
        MM: '%d mesiacov',
        y: 'rok',
        yy: '%d rokov'
      },
      ordinal: n => `${n}.`,
      formats: {
        LT: 'H:mm',
        LTS: 'H:mm:ss',
        L: 'DD. MM. YYYY',
        LL: 'D. MMMM YYYY',
        LLL: 'D. MMMM YYYY H:mm',
        LLLL: 'dddd D. MMMM YYYY H:mm'
      }
    }
    
    dayjs.locale(locale, null, true)
    
    export default locale
    

    PS—@prantlf, can I ask you to check the translate() function? Thanks in advance! :smiley:

    opened by tukusejssirs 37
  • TypeError: dayjs_1.default is not a function

    TypeError: dayjs_1.default is not a function

    When updating the dayjs package from 1.8.0 to 1.8.3, I'm getting this error.

    I changed my import from import * as dayjs from 'dayjs'; to import dayjs from 'dayjs'; which let me compile, but this error what this result.

    Here is the line of code for the error:

    const today = dayjs().format('YYYY-MM-DD');

    ☢️Bug 
    opened by dockleryxk 37
  • locales/tz

    locales/tz

    Update: Day.js Time Zone Plugin https://day.js.org/docs/en/timezone/timezone


    #498

    • reverts to using locale file if its added, you'd basically want to add it first before setting a locale, because I'm not sure that it will be overwritten
    • dd is two letters long when using intl, it doesn't natively support the option
    • won't respect format order when using intl, or repeat items
    • both tz and offset can be added with options
    • doesn't support fallback locales [en-us,en-gb] won't work in intl
    • summary format options like LTS/LLL aren't implemented as I don't know if they're even used
    • it defaults to using libraries default if not format is provided in en locale
    opened by janat08 36
  • ISO weeks (start from monday)?

    ISO weeks (start from monday)?

    There are some handy methods in moment.js like .startOf('isoWeek'), .isoWeekday(1). They are very useful when Monday is the first day of week in current locale.

    I didn't found any similar methods, are they exists?

    enhancement released 
    opened by denisinvader 32
  • 🌟 Day.js 2.0 alpha preview is available

    🌟 Day.js 2.0 alpha preview is available

    The v2 branch is here #2066

    If you have issues with v2, please comment on this issue. Please do not comment on irrelevant content.

    Changelog

    • supports ESM
    Outdated

    The information is outdated, we're planning them released when v3.0.

    Changelog

    2.0.0-alpha.0

    ⚠️ At this very early stage, some plugins and locales have not been implemented. (PR welcomed) ⚠️ v2 has been rewritten. The compatibility of any private API is not guaranteed.

    Breaking Change

    • dayjs.locale(preset, object, isLocal) => dayjs.locale(preset, isLocal, object)
    • drop support of node < 14.19.0
    • importing plugins or locale (maybe will be changed in the future) ~~import 'dayjs/plugin/isToday'~~ > import 'dayjs/dist/plugin/isToday'

    Feature

    • supports ESM
    • rewrite using TypeScript
    opened by sxzz 29
  • TimeZone - a plugin with time zone support for parsing and formatting strings

    TimeZone - a plugin with time zone support for parsing and formatting strings

    Day.js Time Zone Plugin https://day.js.org/docs/en/timezone/timezone






    Attempts to implement #323 by introducing the TimeZone plugin.

    It uses the IANA time zone database, packed to a JSON format by moment-time-zone and with a simple interface to it provided by timezone-support.

    Although the Intl time zone support has been introduced, there are still browsers or platforms, which do not support it and would not mind "paying for" the support by including more JavaScript code. The size of the time zone supporting library without the Day.js plugin: source 185 kB, minified 182 kB, gzipped 24 kB.

    I can imagine adding support for remembering the time zone for future calls to .format() as discussed at #46.

    Time zone conversions are possible already without an additional API. Jut use UTC date from one Day.js object and format it the target time zone using the other (or the same) Day.js object.

    opened by prantlf 29
  •  Property 'fromNow' does not exist on type 'Dayjs'

    Property 'fromNow' does not exist on type 'Dayjs'

    I'm using the relativeTime plugin in my .ts file

    Importing is done in below manner : - import * as dayjs from 'dayjs'; import relativeTime from 'dayjs/plugin/relativeTime'; dayjs.extend(relativeTime);

    I've also tried to change the import statement as: import dayjs from 'dayjs'; But started throwing new error as no exported member

    Now when I'm using in the fromNow function as: - dayjs(this.created_at).fromNow(); the compiler is throwing an error

    Property 'fromNow' does not exist on type 'Dayjs' I'm using "dayjs": "^1.7.4", version

    What's the with usage? How can I fix this?

    @iamkun Please address this issue

    released 
    opened by yashwp 29
  • Initial work to make plugins type-safe (typescript)

    Initial work to make plugins type-safe (typescript)

    All changes are in types only, and and thus not breaking changes as far as runtime is concerned.

    The changes are essentially an implementation of option 3 from my comment in #364.

    Do note that it will break plugins that reference PluginFunc, since it now requires a generic (this can be avoided with default generics, but there's a good point not to give defaults in this case. I can expand on this if needed).

    I also made a small change to the type of UnitType to allow more units to be passed in, seeing that the source allows it. I can pull that into a separate PR if needed.

    Lastly, I moved the index.d.ts file into the /src folder, for easier automatic detection by tsc inside the repo. This is unsolved (together with the definition file for the relativeTime plugin I made as an example. Both of these files should be copied over and included in the final bundle.

    Update: adding types for so-called "static plugins" is now possible (like the customParseFormat plugin, which modifies the dayjs namespace, and not the prototype). There is a little overhead for plugin type authors, but it's very minimal. See the type for customParseFormat plugin as an example.

    opened by bengry 28
  • Implement simple fromNow() API based on timeago.js

    Implement simple fromNow() API based on timeago.js

    Implementation of the fromNow() function of moment based on timeago.js . The API is as follows:

    dayjs().fromNow(dayjs)
    

    And returns a string with the time passed between the two dates with the following format:

    Just now , in X hours/years/months , X hours/years/months ago ...
    

    For the sake of simplicity, the time is adjusted to the highest time measurement instead of being unit defined, e.g 60 days will be 2 months , 94670856 seconds will be 2 years, and 76 seconds will be 1 minute , and so on.

    Tests are also implemented and passing, which compare the function output with timeago() in various scenarios.

    TO DO: Maybe adding some template to change the locale of the messages (change X years ago for X years, or just X...) or to be able to customize them as moment, but to be fair I don't see it as necessary, just adding the chinese version should be it, but it could certainly be implemented. Adding a few lines of code, the version with a specific unit specified (I want it defined in weeks), can also be put, but that would be maybe complicating it a lot?

    opened by aalises 28
  • Add Request day().add(object)

    Add Request day().add(object)

    Describe the bug Hi,

    I kind of like this project, I'd like to use it to add an object instead of just using add(value: number, unit: string). I was using moment before but im moving into using dayjs because its way smaller.

    Expected behavior const maxTimestamp = moment(this.endDate.value.valueOf()) .utc() .startOf('day'); maxTimestamp.add({ hours: minTime.slice(0, 2), minutes: minTime.slice(3, 5) }); Trying to switch that into: const maxTimestamp = day(this.endDate.value.valueOf()) .utc() .startOf('day'); maxTimestamp.add({ hours: minTime.slice(0, 2), minutes: minTime.slice(3, 5) }); Information

    • Day.js Version [e.g. v1.0.0]
    • OS: [e.g. iOS]
    • Browser [e.g. chrome 62]
    opened by hijazikaram 25
  • dayjs('2023-01-05 03:45:00').tz('Africa/Accra', true).format('YYYY-MM-DDTHH:mm:ss.SSSZZ')

    dayjs('2023-01-05 03:45:00').tz('Africa/Accra', true).format('YYYY-MM-DDTHH:mm:ss.SSSZZ')

    Describe the bug The time will change after setting the time format of the time zone offset 0

    Expected behavior time does not change

    Information

    • Day.js Version [e.g. v1.11.7]
    • OS: [e.g. iOS]
    • Browser [e.g. chrome 108]
    • Time zone: [e.g. GMT-00:00 DST (Pacific Daylight Time)]
    opened by jiememe2021 0
  • export = locale in index.d.ts doesnt allow synthetic import

    export = locale in index.d.ts doesnt allow synthetic import

    Describe the bug When I want to import dayjs as synthetic import in my lib, I get the following error :

    export = dayjs; ~~~~~~~~~~~~~~~ This module is declared with using 'export =', and can only be used with a default import when using the 'allowSyntheticDefaultImports' flag

    Expected behavior Application can build with this line : "import dayjs from 'dayjs';"

    Information

    • Day.js Version [e.g. v1.11.7]
    • OS: [Windows]
    • Browser: Chrome 108
    • Time zone: GMT +1
    opened by Alex33400 0
  • isoWeek() returns wrong value

    isoWeek() returns wrong value

    Describe the bug .isoWeek(week) should set proper week

    Expected behavior .isoWeek(week) sets week from previous year instead

    Information

    • Day.js Version v1.11.7
    • OS: Windows
    • Browser: Chrome 108
    • Time zone: GMT +1

    Reproduction code:

    const dayjs = require("dayjs");
    var isoWeek = require('dayjs/plugin/isoWeek')
    dayjs.extend(isoWeek);
    
    year = 2021;
    week = 51;
    
    date = dayjs();
    date2021 = dayjs().year(year);
    date2021week51 = dayjs().year(year).isoWeek(week);
        
    console.log(date); // correct
    console.log(date2021); // correct 
    console.log(date2021week51); // incorrect - should be week 51 of year 2021, not 2020
    

    https://runkit.com/63b3f5320465cd00088b7bd9/63b3f5e70465cd00088b7c55

    opened by Daszczu 0
  • the result of add and subtract is different to php

    the result of add and subtract is different to php

    js code: date = '2022-12-31'

    $result = dayjs(date).add(6, 'month').subtract(1, 'day').format('YYYY-MM-DD')

    $result is 2023-6-29

    PHP code: $start = '2022-12-31'; $end = strtotime("{$start} +6 month -1 day"); $result = date('Y-m-d', $end); $result is 2023-6-30

    opened by zeroone2005 0
  • weekOfYear returns wrong result for the beginning of this year

    weekOfYear returns wrong result for the beginning of this year

    Describe the bug I want to get last year date which matches the same week year and day of a date with a fr locale. I also noticed that these errors are no longer happening after the 30 january 2023

    Expected behavior Monday 02 january 2023 should be Monday 03 January 2022 but the result is : Monday 11 January 2021

    You can see it here: https://runkit.com/embed/u1xvs7v4jax7

    Information

    • Day.js Version: v1.11.7
    • Browser: chrome 108
    opened by UlrichHP 1
Releases(v1.11.7)
Owner
internet noob (╯' - ')╯ ┻━┻
null
🕑 js-joda is an immutable date and time library for JavaScript.

js-joda is an immutable date and time library for JavaScript. It provides a simple, domain-driven and clean API based on the ISO8601 calendar.

null 1.5k Dec 27, 2022
Duet Date Picker is an open source version of Duet Design System’s accessible date picker. Try live example at https://duetds.github.io/date-picker/

Duet Date Picker Duet Date Picker is an open source version of Duet Design System’s accessible date picker. Duet Date Picker can be implemented and us

Duet Design System 1.6k Jan 6, 2023
Timezone support for moment.js

Moment Timezone IANA Time zone support for Moment.js Project Status Moment-Timezone is an add-on for Moment.js. Both are considered legacy projects, n

Moment.js 3.7k Jan 1, 2023
Replace moment with dayjs, support use in vite, rollup, webpack

Replace moment with dayjs, support use in vite, rollup, webpack

null 11 Dec 6, 2022
Create Persian Calendar as html helper with tag builder c# , and convert selected persian date to gregorian date

Persian-Calendar Use JS,Html,CSS,C# White theme for Persian Calendar , easy to use. Create Persian Calendar as html helper. Use Tag builder in c# for

Tareq Awwad 4 Feb 28, 2022
A date picker web component, and spiritual successor to duet date picker

<date-picker> A date picker web component, based on duet date picker, except authored with Lit and using shadow DOM. This is a work in progress. Todo:

Nick Williams 25 Aug 3, 2022
⏳ Modern JavaScript date utility library ⌛️

date-fns provides the most comprehensive, yet simple and consistent toolset for manipulating JavaScript dates in a browser & Node.js. ?? Documentation

date-fns 30.6k Dec 29, 2022
CalendarPickerJS - A minimalistic and modern date-picker component/library 🗓️👨🏽‍💻 Written in Vanilla JS

CalendarPickerJS The simple and pretty way to let a user select a day! Supports all major browser. Entirely written in Vanilla JavaScript with no depe

Mathias Picker 15 Dec 6, 2022
:clock8: :hourglass: timeago.js is a tiny(2.0 kb) library used to format date with `*** time ago` statement.

timeago.js timeago.js is a nano library(less than 2 kb) used to format datetime with *** time ago statement. eg: '3 hours ago'. i18n supported. Time a

hustcc 4.9k Jan 4, 2023
This library provide a fast and easy way to work with date.

Calendar.js Calendar.js provide a fast way to work with dates when you don't wanna deal with hours, minute, second and so on. It means that Calendar.j

ActuallyNotaDev 3 Apr 27, 2022
Reusable date picker component for React

React DayPicker DayPicker is a reusable date picker component for React. $ npm install react-day-picker@next Beta version ⚠️ This branch is for the ne

Giampaolo Bellavite 4.8k Dec 28, 2022
DEPRECATED: Timezone-enabled JavaScript Date object. Uses Olson zoneinfo files for timezone data.

TimezoneJS.Date A timezone-enabled, drop-in replacement for the stock JavaScript Date. The timezoneJS.Date object is API-compatible with JS Date, with

Matthew Eernisse 830 Nov 20, 2022
Date() for humans

date Date is an english language date parser for node.js and the browser. For examples and demos, see: http://matthewmueller.github.io/date/ Update: d

Matthew Mueller 1.5k Jan 4, 2023
Lightweight and simple JS date formatting and parsing

fecha Lightweight date formatting and parsing (~2KB). Meant to replace parsing and formatting functionality of moment.js. NPM npm install fecha --save

Taylor Hakes 2k Jan 5, 2023
A lightweight, locale aware formatter for strings containing unicode date tokens.

Date Token Format A lightweight (~2kB), locale aware formatter for strings containing unicode date tokens. Usage Install the package using: yarn add d

Donovan Hutchinson 1 Dec 24, 2021
Nepali Date Picker jQuery Plugin 🇳🇵

Nepali Date Picker Nepali Date Picker jQuery Plugin for everyone. ???? Installation npm install nepali-date-picker Demo and Documentation https://leap

Leapfrog Technology 70 Sep 29, 2022
React Native Week Month Date Picker

React Native Week Month Date Picker Date picker with a week and month view Installation npm install react-native-week-month-date-picker Dependencies T

Noona 119 Dec 27, 2022
Easy to get a date.

date2data 테이블에 날짜별 데이터 넣을 때마다 새로 객체 만들어서 작업하기가 매우 귀찮아서 만들었다. moment.js를 쓰기에는 구현하고자 하는 내용이 너무 가벼웠음 Install npm i date2data Usage import {getMonthlyDate

Duho Kim 3 Apr 12, 2022
A tiny and fast zero-dependency date-picker built with vanilla Javascript and CSS.

A tiny zero-dependency and framework-agnostic date picker that is incredibly easy to use! Compatible with any web UI framework, vanilla JS projects, and even HTML-only projects!

Nezar 1 Jan 22, 2021