Coder Social home page Coder Social logo

iamkun / dayjs Goto Github PK

View Code? Open in Web Editor NEW
45.7K 283.0 2.2K 5.4 MB

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

Home Page: https://day.js.org

License: MIT License

JavaScript 100.00%
time date date-formatting datetime moment dayjs

dayjs's Introduction

English | 简体中文 | 日本語 | Português Brasileiro | 한국어 | Español (España) | Русский | Türkçe | සිංහල | עברית

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 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

Usage Trend

Sponsors

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

[Become a sponsor via Github] [Become a sponsor via OpenCollective]

                                                               BestKru                  

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.

dayjs's People

Contributors

aalises avatar alik0211 avatar csvwolf avatar dyoshikawa avatar frankxuzy avatar frondor avatar g1eny0ung avatar guisturdy avatar huruji avatar hustcc avatar iamkun avatar imwh0im avatar mahammedzkhan avatar mariomc avatar naulacambra avatar ohbarye avatar prantlf avatar revilationer avatar rn4n avatar saknarak avatar sameer-ahmed avatar schiem avatar semantic-release-bot avatar shadowpark avatar styfle avatar vilanz avatar waseemahmad31 avatar xx45 avatar zardoy avatar zazzaz avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

dayjs's Issues

dayjs init data seems not right

When I init data like this, not like moment.js can make right way to parse the Date String.

console.log(dayjs('2018-01'))

output:
Fri Dec 01 2017 00:00:00 GMT+0800 (CST

But I can solve by pass the Date, and init with new Date(string).

console.log(dayjs(new Date('2018-01')))

output:
Mon Jan 01 2018 08:00:00 GMT+0800 (CST)

希望你能看得懂...

Locales?

will there be any locales avaliable?

Constructor with custom format

moment.js has wide usable feature to make date from custom strings. For example:
moment('2018-02-01', 'YYYY-DD-MM')
or
moment('02-2018-01', 'DD-YYYY-MM');

Do we want to support this feature in our core? I'm not sure how to implement it in minimalist way, but I think we need to rewrite .format function somehow to avoid copy-paste of code. If you will be agree, guys, that we need to have this feature - I'll think about it.

Alternate constructor support?

I've been traipsing through the documentation and the code, and didn't see anything, so if it's there and I missed it I apologize.

Is there a plan to support other constructors for different use cases, the way moment.utc and moment.unix operate? Everything currently appears to be local timezones only.

TODO

Checklist

  • UTC plugin support
  • fromNow Plugin (@aalises doing...)
  • More locales (PR welcome)
  • Chinese doc 【欢迎提PR】 中文文档补齐 目前format表格需要补充 插件和国际化需要翻译
  • CHANGELOG
  • Plugin && Locale

server sync method

Any method for server sync method date time if client datetime is not correct?

Differences to moment?

Could you add a section to the README.md that explains the differences to moment? Why is it faster/smaller? What features are missing? Are the parts of the API that are different? What was your motivation to "reinvent" the wheel?

week api?

怎么没有week相关的api呢?如获取今天是这周第几天,星期的开始,结束等,谢谢

Default to current time for isBefore/isAfter

In the momentjs API, calling momentObj.isBefore() (without an argument) returns whether the momentObj is before the current time.

Calling dayjsObj.isBefore() results in TypeError: Cannot read property 'valueOf' of undefined.

It'd be nice to have the same behavior as moment in this case, or at least note that it's different in the README. 🙂

Compute a human-readable difference between two date-times?

(I did a quick Google for this and found nothing)

I would like to format the difference between two dates so that it is easily human-readable.

For example:

  • Just now
  • 1 hour ago
  • 3 days ago
  • etc...

Does daysjs provide this functionality?

Logo Contribution

Hi @xx45,
I just saw your app and if you need a new logo or widget design i can help you
I am waiting for you reply

No ordinal number spelling after the day automatically when using format()

Using D or DD for the day format string doesn't add the ordinal number spelling such as 1st, 2nd, 3rd, 4th, etc.

dayjs('2016-01-24 01:23:45').format('MMMM D YYYY, h:mm:ss a')

outputs:

"January 24 2016, 1:23:45 am"

We need a way to automatically detect which ordinal number spelling goes after the day

HH:mm error

dayjs(10000).format('HH:mm')
return "03:0"
but must "03:00"

"mm | 00-59 | The minute, 2-digits"

Add motivation to README

In my opinion there should probably be a section of the README dedicated to explaining the "why?" and the "what?" of dayjs.

  • Why should you pick dayjs over an established library such as momentjs?
  • What makes dayjs unique?
  • Why was it created?
  • What problems does it solve, what holes in the market does it fill?

Etc. You get it.

Road Map 1.6.0

Checklist

  • API Document
  • Typescript Support
  • Unit test use millisecond (ensure accuracy)
  • Browser test *

Getting AM/PM

How do I get AM/PM? There are no options to getting AM/PM I found.

Format error in iOS 11.3

In PC dayjs('2018-09-06T17:00:00.000+0000') return Thu, 06 Sep 2018 17:00:00 GMT
In Iphone dayjs('2018-09-06T17:00:00.000+0000') return Invalid Date

Section showcasing integrations of dayjs

Hi, huge fan of this library! Currently working on moving different projects from moment to dayjs.

I'm wondering if it would be nice to have a section on the README showing projects/integrations that utilize dayjs, mainly ways in which people can start using dayjs? I use React and have been working on the react-dayjs module for displaying dates in React using dayjs, and I saw there is someone working on an dayjs angular pipes module as well.

Just an idea, thanks for the project! :)

Constructor Issues with ISO 8601

dayjs().format()
"2018-04-24T11:21:29-07:00"
dayjs("2018-04-24T11:21:23-07:00").format()
"2018-04-24T11:21:23-07:00"
dayjs("2018-04-24").format()
"2018-04-23T17:00:00-07:00"
dayjs("20180424").format()
"2018-04-24T00:00:00-07:00"

It seems your regex isn't catching it properly.
A simple fix for just ISO formatted dates:

if (/(\d{4}-\d{2}-\d{1,2})/.test(configStr)) {
//Date only
const date = regEx[1].split('-');
return new Date(date[0], date[1] - 1, date[2]);
} else if (
/^(-?(?:[1-9][0-9]*)?[0-9]{4})-(1[0-2]|0[1-9])-(3[01]|0[1-9]|[12][0-9])T(2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9])(.[0-9]+)?(Z)?$/.test(
configStr
)
) {
//Full 8601 String
return new Date(configStr);
} else if (/(\d{4}-\d\d-\d\d)(.)(\d\d:\d\d)/.test(configStr)) {
//ISO Pattern: YYYY-MM-DD HH:mm
const regEx = /(\d{4}-\d\d-\d\d)(.)(\d\d:\d\d)/g.exec(configStr);
const date = regEx[1].split('-');
const time = regEx[3].split(':');
return new Date(date[0], date[1] - 1, date[2], time[0], time[1]);
}

If you really want to be robust check out some of Moment's constructor.

parsing difference with time offset between moment and dayjs

Hello, firstly thanks for your effort for this plugin.
I found an issue with parsing the same date between moment and dayjs
image
as you can see here dayjs is not adding the timezone shift when you call format method.
am i doing something wrong ?

format() function is not showing correct timezone

According to docs at github, the function dayjs().format() (without any arguments) should return a timestamp with timezone like "2018-05-06T14:31:02+05:30" (My timezone is +5:30). But instead it's returning "2018-05-06T14:31:020500:00". I checked with the code, even test for Format no formatStr is failing with :


    expect(received).toBe(expected) // Object.is equality

    Expected value to be:
      "2018-05-06T14:26:00+05:30"
    Received:
      "2018-05-06T14:26:000500:00"

dayjs().endOf('month') Error

console print: Cannot read property 'apply' of undefined
v:1.5.13
code:

dayjs().startOf('month') // can run
dayjs().endOf('month') // Error

Improvements on the introduction.

For the introduction in README.md I think we should mention what day.js can do. Shouldn't wait for the user scroll to the API reference and spend some time to understand what is going on.

I think we should add some introduction about the functions right before the sentence below:

Day.js is a minimalist JavaScript library for modern browsers with a largely Moment.js-compatible API. If you use Moment.js, you already know how to use Day.js.

Actual browser support?

Hi there! First off, REALLY nice work with this!

My question: can you clarify browser support for this? "All browsers support" is cute, but does that mean you support, for example, IE6? All modern browsers (and if so what's the line that makes a browser "modern")?

Thanks!

Missing several format options

The Moment docs have a number of format options which are missing from DayJS. Some of them, like the locality specific ones, I think it makes sense to exclude, but there are others that are missing that could be included without having a serious impact on the library size.

Here are the missing formats that I propose are added:

  • Q - Quarter of the year
  • Do - Day of month with ordinal
  • DDD/DDDD - Day of year
  • X - Unix timestamp
  • x - Unix timestamp with ms
  • h/hh - 12 hour time
  • k/kk - 24 hour time beginning at 1
  • a/A - Post and ante meridiem
  • S/SS/SSS - Milliseconds

However, this would nearly double the size of the format function, which isn't ideal. Are there any of those that shouldn't be added?

Should dates be fixed to be valid?

Hello! I'm new to this project, and had been using Moment in the past, and I noticed that when I input a date such as: dayjs('2015-02-29') (which doesn't exist) it automatically fixes the date to read 2015-03-01.

I suppose I'm just checking to see if this behavior is really wanted; it seems kind of bizarre to have dates wrap around like this and correct themselves. If this is the wanted behavior, then completely ignore this, but I just feel like the date 02-29 in non-leap years, and other nonexistent dates, should be invalid rather than changed.

There are errors!

dayjs(0).format('mm:ss')
return 58:34
moment(0).format('mm:ss')
return 00:00

Format need to check date is invalid & Don't format dayjs(null)

const dayjs = require('dayjs');
const moment = require('moment');

console.log('\n=== dayjs ===');
console.log(dayjs('wtf').format());
console.log(dayjs(null).format());

console.log('\n=== moment ===');
console.log(moment('wtf').format());
console.log(moment(null).format());

That code will print:

=== dayjs ===
NaN-NaN-NaNTNaN:NaN:NaN++N:00
2018-04-27T10:38:31+08:00

=== moment ===
Deprecation warning: value provided is not in a recognized RFC2822 or ISO format. moment construction falls back to js Date(), which is not reliable across all browsers and versions. Non RFC2822/ISO date formats are discouraged and will be removed in an upcoming major
 release. Please refer to http://momentjs.com/guides/#/warnings/js-date/ for more info.
Arguments:
[0] _isAMomentObject: true, _isUTC: false, _useUTC: false, _l: undefined, _i: wtf, _f: undefined, _strict: undefined, _locale: [object Object]
Error
    at Function.createFromInputFallback (/Users/ahonn/Desktop/test/node_modules/moment/moment.js:320:98)
    at configFromString (/Users/ahonn/Desktop/test/node_modules/moment/moment.js:2368:15)
    at configFromInput (/Users/ahonn/Desktop/test/node_modules/moment/moment.js:2594:13)
    at prepareConfig (/Users/ahonn/Desktop/test/node_modules/moment/moment.js:2577:13)
    at createFromConfig (/Users/ahonn/Desktop/test/node_modules/moment/moment.js:2544:44)
    at createLocalOrUTC (/Users/ahonn/Desktop/test/node_modules/moment/moment.js:2631:16)
    at createLocal (/Users/ahonn/Desktop/test/node_modules/moment/moment.js:2635:16)
    at hooks (/Users/ahonn/Desktop/test/node_modules/moment/moment.js:12:29)
    at Object.<anonymous> (/Users/ahonn/Desktop/test/index.js:16:13)
    at Module._compile (module.js:652:30)
Invalid date
Invalid date

You need to check date is invalid, dayjs('wtf') preferably returns Invalid date.
And dayjs(null) should not return current date, null is not equal to undefined.

Type definitions

Could we include a typing declaration for use with TypeScript?

The automated release is failing 🚨

🚨 The automated release from the master branch failed. 🚨

I recommend you give this issue a high priority, so other packages depending on you could benefit from your bug fixes and new features.

You can find below the list of errors reported by semantic-release. Each one of them has to be resolved in order to automatically publish your package. I’m sure you can resolve this 💪.

Errors are usually caused by a misconfiguration or an authentication problem. With each error reported below you will find explanation and guidance to help you to resolve it.

Once all the errors are resolved, semantic-release will release your package the next time you push a commit the master branch. You can also manually restart the failed CI job that runs semantic-release.

If you are not sure how to resolve this, here is some links that can help you:

If those don’t help, or if this issue is reporting something you think isn’t right, you can always ask the humans behind semantic-release.


No npm token specified.

An npm token must be created and set in the NPM_TOKEN environment variable on your CI environment.

Please make sure to create an npm token and to set it in the NPM_TOKEN environment variable on your CI environment. The token must allow to publish to the registry https://registry.npmjs.org/.


Good luck with your project ✨

Your semantic-release bot 📦🚀

Difference test failure

Getting the following error while running the test suite.

 FAIL  test/display.test.js
  ● Difference › diff -> in seconds, days, weeks, months, quarters, years

    expect(received).toBe(expected) // Object.is equality

    Expected value to be:
      -86403600
    Received:
      -86400000

      131 |     const units = ['seconds', 'days', 'weeks', 'months', 'quarters', 'years']
      132 |     units.forEach((unit) => {
    > 133 |       expect(dayjsA.diff(dayjsB, unit)).toBe(momentA.diff(momentB, unit))
      134 |       expect(dayjsA.diff(dayjsB, unit, true)).toBe(momentA.diff(momentB, unit, true))
      135 |       expect(dayjsA.diff(dayjsC, unit)).toBe(momentA.diff(momentC, unit))
      136 |       expect(dayjsA.diff(dayjsC, unit, true)).toBe(momentA.diff(momentC, unit, true))

      at test/display.test.js:133:41
          at Array.forEach (<anonymous>)
      at Object.<anonymous> (test/display.test.js:132:11)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.