From 173cb9a83e2fc20f89e380d34c5060e9ddff53a6 Mon Sep 17 00:00:00 2001 From: splashwizard Date: Thu, 14 Feb 2019 11:42:54 +0800 Subject: [PATCH 01/25] docs: prettier docs --- docs/en/API-reference.md | 112 ++++++------- docs/en/I18n.md | 33 ++-- docs/en/Installation.md | 12 +- docs/en/Plugin.md | 101 ++++++------ docs/es-es/API-reference.md | 112 ++++++------- docs/es-es/I18n.md | 29 ++-- docs/es-es/Installation.md | 12 +- docs/es-es/Plugin.md | 95 +++++------ docs/es-es/README-es-es.md | 28 ++-- docs/ja/API-reference.md | 318 ++++++++++++++++++------------------ docs/ja/I18n.md | 27 +-- docs/ja/Installation.md | 10 +- docs/ja/Plugin.md | 176 ++++++++++---------- docs/ja/README-ja.md | 29 ++-- docs/ko/API-reference.md | 143 ++++++++-------- docs/ko/I18n.md | 27 ++- docs/ko/Installation.md | 10 +- docs/ko/Plugin.md | 167 ++++++++++--------- docs/ko/README-ko.md | 28 ++-- docs/pt-br/API-reference.md | 164 ++++++++++--------- docs/pt-br/I18n.md | 52 +++--- docs/pt-br/Installation.md | 12 +- docs/pt-br/Plugin.md | 170 ++++++++++--------- docs/pt-br/README-pt-br.md | 33 ++-- docs/zh-cn/API-reference.md | 314 +++++++++++++++++++++++------------ docs/zh-cn/I18n.md | 36 ++-- docs/zh-cn/Installation.md | 9 +- docs/zh-cn/Plugin.md | 177 ++++++++++---------- docs/zh-cn/README.zh-CN.md | 29 +++- 29 files changed, 1368 insertions(+), 1097 deletions(-) diff --git a/docs/en/API-reference.md b/docs/en/API-reference.md index 49370bb5..b4e8986c 100644 --- a/docs/en/API-reference.md +++ b/docs/en/API-reference.md @@ -65,7 +65,7 @@ The `Dayjs` object is immutable, that is, all API operations that change the `Da Calling it without parameters returns a fresh `Dayjs` object with the current date and time. ```js -dayjs(); +dayjs() ``` Day.js also parses other date formats. @@ -73,13 +73,13 @@ Day.js also parses other date formats. #### [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) string ```js -dayjs("2018-04-04T16:00:00.000Z"); +dayjs('2018-04-04T16:00:00.000Z') ``` #### Native Javascript Date object ```js -dayjs(new Date(2018, 8, 18)); +dayjs(new Date(2018, 8, 18)) ``` #### Unix Timestamp (milliseconds) @@ -87,7 +87,7 @@ dayjs(new Date(2018, 8, 18)); Returns a `Dayjs` from a Unix timestamp (milliseconds since the Unix Epoch) ```js -dayjs(1318781876406); +dayjs(1318781876406) ``` ### Unix Timestamp (seconds) `.unix(value: number)` @@ -95,8 +95,8 @@ dayjs(1318781876406); Returns a `Dayjs` from a Unix timestamp (seconds since the Unix Epoch) ```js -dayjs.unix(1318781876); -dayjs.unix(1318781876.721); +dayjs.unix(1318781876) +dayjs.unix(1318781876.721) ``` ### Custom Parse Format @@ -108,8 +108,8 @@ dayjs.unix(1318781876.721); Returns a cloned `Dayjs`. ```js -dayjs().clone(); -dayjs(dayjs("2019-01-25")); // passing a Dayjs object to a constructor will also clone it +dayjs().clone() +dayjs(dayjs('2019-01-25')) // passing a Dayjs object to a constructor will also clone it ``` ### Validation `.isValid()` @@ -117,7 +117,7 @@ dayjs(dayjs("2019-01-25")); // passing a Dayjs object to a constructor will also Returns a `boolean` indicating whether the `Dayjs`'s date is valid. ```js -dayjs().isValid(); +dayjs().isValid() ``` ## Get and Set @@ -127,7 +127,7 @@ dayjs().isValid(); Returns a `number` representing the `Dayjs`'s year. ```js -dayjs().year(); +dayjs().year() ``` ### Month `.month()` @@ -135,7 +135,7 @@ dayjs().year(); Returns a `number` representing the `Dayjs`'s month. Starts at 0 ```js -dayjs().month(); +dayjs().month() ``` ### Day of the Month `.date()` @@ -143,7 +143,7 @@ dayjs().month(); Returns a `number` representing the `Dayjs`'s day of the month. Starts at 1 ```js -dayjs().date(); +dayjs().date() ``` ### Day of the Week `.day()` @@ -151,7 +151,7 @@ dayjs().date(); Returns a `number` representing the `Dayjs`'s day of the week. Starts on Sunday with 0 ```js -dayjs().day(); +dayjs().day() ``` ### Hour `.hour()` @@ -159,7 +159,7 @@ dayjs().day(); Returns a `number` representing the `Dayjs`'s hour. ```js -dayjs().hour(); +dayjs().hour() ``` ### Minute `.minute()` @@ -167,7 +167,7 @@ dayjs().hour(); Returns a `number` representing the `Dayjs`'s minute. ```js -dayjs().minute(); +dayjs().minute() ``` ### Second `.second()` @@ -175,7 +175,7 @@ dayjs().minute(); Returns a `number` representing the `Dayjs`'s second. ```js -dayjs().second(); +dayjs().second() ``` ### Millisecond `.millisecond()` @@ -183,7 +183,7 @@ dayjs().second(); Returns a `number` representing the `Dayjs`'s millisecond. ```js -dayjs().millisecond(); +dayjs().millisecond() ``` ### Set `.set(unit: string, value: number)` @@ -191,9 +191,9 @@ dayjs().millisecond(); Returns a `Dayjs` with the applied changes. ```js -dayjs().set("date", 1); -dayjs().set("month", 3); // April -dayjs().set("second", 30); +dayjs().set('date', 1) +dayjs().set('month', 3) // April +dayjs().set('second', 30) ``` #### List of all available units @@ -214,10 +214,10 @@ dayjs().set("second", 30); `Dayjs` objects can be manipulated in many ways. ```js -dayjs("2019-01-25") - .add(1, "day") - .subtract(1, "year") - .toString(); // Fri, 26 Jan 2018 00:00:00 GMT +dayjs('2019-01-25') + .add(1, 'day') + .subtract(1, 'year') + .toString() // Fri, 26 Jan 2018 00:00:00 GMT ``` ### Add `.add(value: number, unit: string)` @@ -225,7 +225,7 @@ dayjs("2019-01-25") Returns a cloned `Dayjs` with a specified amount of time added. ```js -dayjs().add(7, "day"); +dayjs().add(7, 'day') ``` ### Subtract `.subtract(value: number, unit: string)` @@ -233,7 +233,7 @@ dayjs().add(7, "day"); Returns a cloned `Dayjs` with a specified amount of time subtracted. ```js -dayjs().subtract(7, "year"); +dayjs().subtract(7, 'year') ``` ### Start of Time `.startOf(unit: string)` @@ -241,7 +241,7 @@ dayjs().subtract(7, "year"); Returns a cloned `Dayjs` set to the start of the specified unit of time. ```js -dayjs().startOf("week"); // Depends on `weekStart` in locale +dayjs().startOf('week') // Depends on `weekStart` in locale ``` ### End of Time `.endOf(unit: string)` @@ -249,7 +249,7 @@ dayjs().startOf("week"); // Depends on `weekStart` in locale Returns a cloned `Dayjs` set to the end of the specified unit of time. ```js -dayjs().endOf("month"); +dayjs().endOf('month') ``` ## Displaying @@ -260,11 +260,11 @@ Returns a `string` with the `Dayjs`'s formatted date. To escape characters, wrap them in square or curly brackets (e.g. `[G] {um}`). ```js -dayjs().format(); // current date in ISO6801, without fraction seconds e.g. '2020-04-02T08:02:17-05:00' +dayjs().format() // current date in ISO6801, without fraction seconds e.g. '2020-04-02T08:02:17-05:00' -dayjs("2019-01-25").format("{YYYY} MM-DDTHH:mm:ssZ[Z]"); // '{2019} 01-25T00:00:00-02:00Z' +dayjs('2019-01-25').format('{YYYY} MM-DDTHH:mm:ssZ[Z]') // '{2019} 01-25T00:00:00-02:00Z' -dayjs("2019-01-25").format("DD/MM/YYYY"); // '25/01/2019' +dayjs('2019-01-25').format('DD/MM/YYYY') // '25/01/2019' ``` #### List of all available formats @@ -305,12 +305,12 @@ dayjs("2019-01-25").format("DD/MM/YYYY"); // '25/01/2019' Returns a `number` indicating the difference of two `Dayjs`s in the specified unit. ```js -const date1 = dayjs("2019-01-25"); -const date2 = dayjs("2018-06-05"); -date1.diff(date2); // 20214000000 -date1.diff(date2, "month"); // 7 -date1.diff(date2, "month", true); // 7.645161290322581 -date1.diff(date2, "day"); // 233 +const date1 = dayjs('2019-01-25') +const date2 = dayjs('2018-06-05') +date1.diff(date2) // 20214000000 +date1.diff(date2, 'month') // 7 +date1.diff(date2, 'month', true) // 7.645161290322581 +date1.diff(date2, 'day') // 233 ``` ### Unix Timestamp (milliseconds) `.valueOf()` @@ -318,7 +318,7 @@ date1.diff(date2, "day"); // 233 Returns the `number` of milliseconds since the Unix Epoch for the `Dayjs`. ```js -dayjs("2019-01-25").valueOf(); // 1548381600000 +dayjs('2019-01-25').valueOf() // 1548381600000 ``` ### Unix Timestamp (seconds) `.unix()` @@ -326,7 +326,7 @@ dayjs("2019-01-25").valueOf(); // 1548381600000 Returns the `number` of seconds since the Unix Epoch for the `Dayjs`. ```js -dayjs("2019-01-25").unix(); // 1548381600 +dayjs('2019-01-25').unix() // 1548381600 ``` ### UTC Offset (minutes) `.utcOffset()` @@ -334,7 +334,7 @@ dayjs("2019-01-25").unix(); // 1548381600 Returns the UTC offset in minutes for the `Dayjs`. ```js -dayjs().utcOffset(); +dayjs().utcOffset() ``` ### Days in the Month `.daysInMonth()` @@ -342,7 +342,7 @@ dayjs().utcOffset(); Returns the `number` of days in the `Dayjs`'s month. ```js -dayjs("2019-01-25").daysInMonth(); // 31 +dayjs('2019-01-25').daysInMonth() // 31 ``` ### As Javascript Date `.toDate()` @@ -350,7 +350,7 @@ dayjs("2019-01-25").daysInMonth(); // 31 Returns a copy of the native `Date` object parsed from the `Dayjs` object. ```js -dayjs("2019-01-25").toDate(); +dayjs('2019-01-25').toDate() ``` ### As Array `.toArray()` @@ -358,7 +358,7 @@ dayjs("2019-01-25").toDate(); Returns an `array` that mirrors the parameters from new Date(). ```js -dayjs("2019-01-25").toArray(); // [ 2019, 0, 25, 0, 0, 0, 0 ] +dayjs('2019-01-25').toArray() // [ 2019, 0, 25, 0, 0, 0, 0 ] ``` ### As JSON `.toJSON()` @@ -366,7 +366,7 @@ dayjs("2019-01-25").toArray(); // [ 2019, 0, 25, 0, 0, 0, 0 ] Returns the `Dayjs` formatted in an ISO8601 `string`. ```js -dayjs("2019-01-25").toJSON(); // '2019-01-25T02:00:00.000Z' +dayjs('2019-01-25').toJSON() // '2019-01-25T02:00:00.000Z' ``` ### As ISO 8601 String `.toISOString()` @@ -374,7 +374,7 @@ dayjs("2019-01-25").toJSON(); // '2019-01-25T02:00:00.000Z' Returns the `Dayjs` formatted in an ISO8601 `string`. ```js -dayjs("2019-01-25").toISOString(); // '2019-01-25T02:00:00.000Z' +dayjs('2019-01-25').toISOString() // '2019-01-25T02:00:00.000Z' ``` ### As Object `.toObject()` @@ -382,7 +382,7 @@ dayjs("2019-01-25").toISOString(); // '2019-01-25T02:00:00.000Z' Returns an `object` with the date's properties. ```js -dayjs("2019-01-25").toObject(); +dayjs('2019-01-25').toObject() /* { years: 2019, months: 0, date: 25, @@ -397,7 +397,7 @@ dayjs("2019-01-25").toObject(); Returns a `string` representation of the date. ```js -dayjs("2019-01-25").toString(); // 'Fri, 25 Jan 2019 02:00:00 GMT' +dayjs('2019-01-25').toString() // 'Fri, 25 Jan 2019 02:00:00 GMT' ``` ## Query @@ -407,8 +407,8 @@ dayjs("2019-01-25").toString(); // 'Fri, 25 Jan 2019 02:00:00 GMT' Returns a `boolean` indicating whether the `Dayjs`'s date is before the other supplied `Dayjs`'s. ```js -dayjs().isBefore(dayjs()); // false -dayjs().isBefore(dayjs(), "year"); // false +dayjs().isBefore(dayjs()) // false +dayjs().isBefore(dayjs(), 'year') // false ``` ### Is Same `.isSame(compared: Dayjs, unit?: string)` @@ -416,8 +416,8 @@ dayjs().isBefore(dayjs(), "year"); // false Returns a `boolean` indicating whether the `Dayjs`'s date is the same as the other supplied `Dayjs`'s. ```js -dayjs().isSame(dayjs()); // true -dayjs().isSame(dayjs(), "year"); // true +dayjs().isSame(dayjs()) // true +dayjs().isSame(dayjs(), 'year') // true ``` ### Is After `.isAfter(compared: Dayjs, unit?: string)` @@ -425,8 +425,8 @@ dayjs().isSame(dayjs(), "year"); // true Returns a `boolean` indicating whether the `Dayjs`'s date is after the other supplied `Dayjs`'s. ```js -dayjs().isAfter(dayjs()); // false -dayjs().isAfter(dayjs(), "year"); // false +dayjs().isAfter(dayjs()) // false +dayjs().isAfter(dayjs(), 'year') // false ``` ### Is a Dayjs `.isDayjs(compared: any)` @@ -434,14 +434,14 @@ dayjs().isAfter(dayjs(), "year"); // false Returns a `boolean` indicating whether a variable is a dayjs object or not. ```js -dayjs.isDayjs(dayjs()); // true -dayjs.isDayjs(new Date()); // false +dayjs.isDayjs(dayjs()) // true +dayjs.isDayjs(new Date()) // false ``` The operator `instanceof` works equally well: ```js -dayjs() instanceof dayjs; // true +dayjs() instanceof dayjs // true ``` ## Plugin APIs diff --git a/docs/en/I18n.md b/docs/en/I18n.md index ce0c92b3..2f9a8bdd 100644 --- a/docs/en/I18n.md +++ b/docs/en/I18n.md @@ -16,7 +16,7 @@ You are super welcome to add a locale by opening a pull request :+1: #### Changing locale globally -* Returns locale string +- Returns locale string ```js import 'dayjs/locale/es' @@ -28,23 +28,25 @@ dayjs.locale(customizedLocaleObject) // use customize locale dayjs.locale('en') // switch back to default English locale globally ``` -* Changing the global locale doesn't affect existing instances. +- Changing the global locale doesn't affect existing instances. #### Changing locales locally -* Returns a new `Dayjs` object by switching to new locale. +- Returns a new `Dayjs` object by switching to new locale. Exactly the same as `dayjs#locale`, but only use locale in a specific instance. ```js import 'dayjs/locale/es' -dayjs().locale('es').format() // use loaded locale locally +dayjs() + .locale('es') + .format() // use loaded locale locally dayjs('2018-4-28', { locale: 'es' }) // through constructor ``` ## Installation -* Via NPM: +- Via NPM: ```javascript import 'dayjs/locale/es' // load on demand @@ -52,17 +54,22 @@ import 'dayjs/locale/es' // load on demand // import locale_es from 'dayjs/locale/es' -> load and get locale_es locale object dayjs.locale('es') // use locale globally -dayjs().locale('es').format() // use locale in a specific instance +dayjs() + .locale('es') + .format() // use locale in a specific instance ``` -* Via CDN: +- Via CDN: + ```html @@ -75,6 +82,7 @@ You could create your own locale. Feel free to open a pull request to share your locale. Template of a Day.js locale Object. + ```javascript const localeObject = { name: 'es', // name String @@ -85,7 +93,8 @@ const localeObject = { months: 'Enero_Febrero ... '.split('_'), // months Array monthsShort: 'Jan_F'.split('_'), // OPTIONAL, short months Array, use first three letters if not provided ordinal: n => `${n}º`, // ordinal Function (number) => return number + output - formats: { // abbreviated format options allowing localization + formats: { + // abbreviated format options allowing localization LTS: 'h:mm:ss A', LT: 'h:mm A', L: 'MM/DD/YYYY', @@ -93,7 +102,8 @@ const localeObject = { LLL: 'MMMM D, YYYY h:mm A', LLLL: 'dddd, MMMM D, YYYY h:mm A' }, - relativeTime: { // relative time format strings, keep %s %d as the same + relativeTime: { + // relative time format strings, keep %s %d as the same future: 'in %s', // e.g. in 2 hours, %s been replaced with 2hours past: '%s ago', s: 'a few seconds', @@ -112,6 +122,7 @@ const localeObject = { ``` Template of a Day.js locale file. + ```javascript import dayjs from 'dayjs' diff --git a/docs/en/Installation.md b/docs/en/Installation.md index b67f032e..9235767e 100644 --- a/docs/en/Installation.md +++ b/docs/en/Installation.md @@ -2,7 +2,7 @@ You have multiple ways of getting Day.js: -* Via NPM: +- Via NPM: ```console npm install dayjs --save @@ -12,19 +12,19 @@ npm install dayjs --save import dayjs from 'dayjs' // Or CommonJS // var dayjs = require('dayjs'); -dayjs().format(); +dayjs().format() ``` -* Via CDN: +- Via CDN: ```html ``` -* Via download and self-hosting: +- Via download and self-hosting: -Just download the latest version of Day.js at [https://unpkg.com/dayjs/](https://unpkg.com/dayjs/) \ No newline at end of file +Just download the latest version of Day.js at [https://unpkg.com/dayjs/](https://unpkg.com/dayjs/) diff --git a/docs/en/Plugin.md b/docs/en/Plugin.md index 3632b850..7df564c7 100644 --- a/docs/en/Plugin.md +++ b/docs/en/Plugin.md @@ -25,10 +25,10 @@ dayjs.extend(plugin, options) // with plugin options - Via NPM: ```javascript -import dayjs from "dayjs"; -import AdvancedFormat from "dayjs/plugin/advancedFormat"; // load on demand +import dayjs from 'dayjs' +import AdvancedFormat from 'dayjs/plugin/advancedFormat' // load on demand -dayjs.extend(AdvancedFormat); // use plugin +dayjs.extend(AdvancedFormat) // use plugin ``` - Via CDN: @@ -38,7 +38,7 @@ dayjs.extend(AdvancedFormat); // use plugin ``` @@ -49,11 +49,11 @@ dayjs.extend(AdvancedFormat); // use plugin - AdvancedFormat extends `dayjs().format` API to supply more format options. ```javascript -import advancedFormat from "dayjs/plugin/advancedFormat"; +import advancedFormat from 'dayjs/plugin/advancedFormat' -dayjs.extend(advancedFormat); +dayjs.extend(advancedFormat) -dayjs().format("Q Do k kk X x"); +dayjs().format('Q Do k kk X x') ``` List of added formats: @@ -68,7 +68,8 @@ List of added formats: | `x` | 1360013296123 | Unix Timestamp in millisecond | ### LocalizedFormat - - LocalizedFormat extends `dayjs().format` API to supply localized format options. + +- LocalizedFormat extends `dayjs().format` API to supply localized format options. ```javascript import LocalizedFormat from 'dayjs/plugin/localizedFormat' @@ -94,18 +95,18 @@ List of added formats: - RelativeTime adds `.from` `.to` `.fromNow` `.toNow` APIs to formats date to relative time strings (e.g. 3 hours ago). ```javascript -import relativeTime from "dayjs/plugin/relativeTime"; +import relativeTime from 'dayjs/plugin/relativeTime' -dayjs.extend(relativeTime); +dayjs.extend(relativeTime) -dayjs().from(dayjs("1990")); // 2 years ago -dayjs().from(dayjs(), true); // 2 years +dayjs().from(dayjs('1990')) // 2 years ago +dayjs().from(dayjs(), true) // 2 years -dayjs().fromNow(); +dayjs().fromNow() -dayjs().to(dayjs()); +dayjs().to(dayjs()) -dayjs().toNow(); +dayjs().toNow() ``` #### Time from now `.fromNow(withoutSuffix?: boolean)` @@ -143,11 +144,11 @@ Returns the `string` of relative time to X. - IsLeapYear adds `.isLeapYear` API to returns a `boolean` indicating whether the `Dayjs`'s year is a leap year or not. ```javascript -import isLeapYear from "dayjs/plugin/isLeapYear"; +import isLeapYear from 'dayjs/plugin/isLeapYear' -dayjs.extend(isLeapYear); +dayjs.extend(isLeapYear) -dayjs("2000-01-01").isLeapYear(); // true +dayjs('2000-01-01').isLeapYear() // true ``` ### BuddhistEra @@ -157,11 +158,11 @@ dayjs("2000-01-01").isLeapYear(); // true - To calculate BE year manually, just add 543 to year. For example 26 May 1977 AD/CE should display as 26 May 2520 BE (1977 + 543) ```javascript -import buddhistEra from "dayjs/plugin/buddhistEra"; +import buddhistEra from 'dayjs/plugin/buddhistEra' -dayjs.extend(buddhistEra); +dayjs.extend(buddhistEra) -dayjs().format("BBBB BB"); +dayjs().format('BBBB BB') ``` List of added formats: @@ -176,11 +177,11 @@ List of added formats: - IsSameOrAfter adds `.isSameOrAfter()` API to returns a `boolean` indicating if a date is same of after another date. ```javascript -import isSameOrAfter from "dayjs/plugin/isSameOrAfter"; +import isSameOrAfter from 'dayjs/plugin/isSameOrAfter' -dayjs.extend(isSameOrAfter); +dayjs.extend(isSameOrAfter) -dayjs("2010-10-20").isSameOrAfter("2010-10-19", "year"); +dayjs('2010-10-20').isSameOrAfter('2010-10-19', 'year') ``` ### IsSameOrBefore @@ -188,11 +189,11 @@ dayjs("2010-10-20").isSameOrAfter("2010-10-19", "year"); - IsSameOrBefore adds `.isSameOrBefore()` API to returns a `boolean` indicating if a date is same of before another date. ```javascript -import isSameOrBefore from "dayjs/plugin/isSameOrBefore"; +import isSameOrBefore from 'dayjs/plugin/isSameOrBefore' -dayjs.extend(isSameOrBefore); +dayjs.extend(isSameOrBefore) -dayjs("2010-10-20").isSameOrBefore("2010-10-19", "year"); +dayjs('2010-10-20').isSameOrBefore('2010-10-19', 'year') ``` ### IsBetween @@ -200,12 +201,12 @@ dayjs("2010-10-20").isSameOrBefore("2010-10-19", "year"); - IsBetween adds `.isBetween()` API to returns a `boolean` indicating if a date is between two other dates. ```javascript -import isBetween from "dayjs/plugin/isBetween"; +import isBetween from 'dayjs/plugin/isBetween' -dayjs.extend(isBetween); +dayjs.extend(isBetween) -dayjs("2010-10-20").isBetween("2010-10-19", dayjs("2010-10-25"), "year"); -dayjs('2016-10-30').isBetween('2016-01-01', '2016-10-30', null, '[)'); +dayjs('2010-10-20').isBetween('2010-10-19', dayjs('2010-10-25'), 'year') +dayjs('2016-10-30').isBetween('2016-01-01', '2016-10-30', null, '[)') // '[' indicates inclusion, '(' indicates exclusion ``` @@ -214,12 +215,12 @@ dayjs('2016-10-30').isBetween('2016-01-01', '2016-10-30', null, '[)'); - DayOfYear adds `.dayOfYear()` API to returns a `number` indicating the `Dayjs`'s day of the year, or to set the day of the year. ```javascript -import dayOfYear from "dayjs/plugin/dayOfYear"; +import dayOfYear from 'dayjs/plugin/dayOfYear' -dayjs.extend(dayOfYear); +dayjs.extend(dayOfYear) -dayjs("2010-01-01").dayOfYear(); // 1 -dayjs("2010-01-01").dayOfYear(365); // 2010-12-31 +dayjs('2010-01-01').dayOfYear() // 1 +dayjs('2010-01-01').dayOfYear(365) // 2010-12-31 ``` ### WeekOfYear @@ -227,11 +228,11 @@ dayjs("2010-01-01").dayOfYear(365); // 2010-12-31 - WeekOfYear adds `.week()` API to returns a `number` indicating the `Dayjs`'s week of the year. ```javascript -import weekOfYear from "dayjs/plugin/weekOfYear"; +import weekOfYear from 'dayjs/plugin/weekOfYear' -dayjs.extend(weekOfYear); +dayjs.extend(weekOfYear) -dayjs("2018-06-27").week(); // 26 +dayjs('2018-06-27').week() // 26 ``` ### QuarterOfYear @@ -239,11 +240,11 @@ dayjs("2018-06-27").week(); // 26 - QuarterOfYear add `.quarter()` API to return to which quarter of the year belongs a date ```javascript -import quarterOfYear from "dayjs/plugin/quarterOfYear"; +import quarterOfYear from 'dayjs/plugin/quarterOfYear' -dayjs.extend(quarterOfYear); +dayjs.extend(quarterOfYear) -dayjs("2010-04-01").quarter(); // 2 +dayjs('2010-04-01').quarter() // 2 ``` ### CustomParseFormat @@ -253,11 +254,11 @@ dayjs("2010-04-01").quarter(); // 2 To escape characters, wrap them in square brackets (e.g. `[G]`). Punctuation symbols (-:/.()) do not need to be wrapped. ```javascript -import customParseFormat from "dayjs/plugin/customParseFormat"; +import customParseFormat from 'dayjs/plugin/customParseFormat' -dayjs.extend(customParseFormat); +dayjs.extend(customParseFormat) -dayjs("05/02/69 1:02:03 PM -05:00", "MM/DD/YY H:mm:ss A Z"); +dayjs('05/02/69 1:02:03 PM -05:00', 'MM/DD/YY H:mm:ss A Z') // Returns an instance containing '1969-05-02T18:02:03.000Z' ``` @@ -299,19 +300,19 @@ Template of a Day.js plugin. export default (option, dayjsClass, dayjsFactory) => { // extend dayjs() // e.g. add dayjs().isSameOrBefore() - dayjsClass.prototype.isSameOrBefore = function(arguments) {}; + dayjsClass.prototype.isSameOrBefore = function(arguments) {} // extend dayjs // e.g. add dayjs.utc() - dayjsFactory.utc = arguments => {}; + dayjsFactory.utc = arguments => {} // overriding existing API // e.g. extend dayjs().format() - const oldFormat = dayjsClass.prototype.format; + const oldFormat = dayjsClass.prototype.format dayjsClass.prototype.format = function(arguments) { // original format result - const result = oldFormat(arguments); + const result = oldFormat(arguments) // return modified result - }; -}; + } +} ``` diff --git a/docs/es-es/API-reference.md b/docs/es-es/API-reference.md index 151d42ca..ae46d814 100644 --- a/docs/es-es/API-reference.md +++ b/docs/es-es/API-reference.md @@ -65,7 +65,7 @@ El objeto `Dayjs` es inmutable, por lo que toda operación de la API que altere Si se llama al constructor sin parámetros, este devuelve un nuevo objeto `Dayjs` con la fecha y hora actual. ```js -dayjs(); +dayjs() ``` Day.js también analiza otros formatos de fecha. @@ -73,13 +73,13 @@ Day.js también analiza otros formatos de fecha. #### Cadena [ISO 8601](https://es.wikipedia.org/wiki/ISO_8601) ```js -dayjs("2018-04-04T16:00:00.000Z"); +dayjs('2018-04-04T16:00:00.000Z') ``` #### Objeto `Date` nativo ```js -dayjs(new Date(2018, 8, 18)); +dayjs(new Date(2018, 8, 18)) ``` #### Tiempo Unix (milisegundos) @@ -87,7 +87,7 @@ dayjs(new Date(2018, 8, 18)); Devuelve un objeto `Dayjs` a partir de un tiempo unix (milisegundos desde la época Unix). ```js -dayjs(1318781876406); +dayjs(1318781876406) ``` ### Tiempo Unix (segundos) `.unix(value: number)` @@ -95,8 +95,8 @@ dayjs(1318781876406); Devuelve un objeto `Dayjs` a partir de un tiempo Unix (segundos desde la época Unix). ```js -dayjs.unix(1318781876); -dayjs.unix(1318781876.721); +dayjs.unix(1318781876) +dayjs.unix(1318781876.721) ``` ### Custom Parse Format @@ -108,8 +108,8 @@ dayjs.unix(1318781876.721); Devuelve una copia de `Dayjs`. ```js -dayjs().clone(); -dayjs(dayjs("2019-01-25")); // si el constructor recibe un objeto Dayjs también lo clonará +dayjs().clone() +dayjs(dayjs('2019-01-25')) // si el constructor recibe un objeto Dayjs también lo clonará ``` ### Validación `.isValid()` @@ -117,7 +117,7 @@ dayjs(dayjs("2019-01-25")); // si el constructor recibe un objeto Dayjs también Devuelve un dato de tipo `boolean`, que indica si la fecha `Dayjs` es válida o no. ```js -dayjs().isValid(); +dayjs().isValid() ``` ## Get y Set @@ -127,7 +127,7 @@ dayjs().isValid(); Devuelve un dato de tipo `number`, que representa el año del objeto `Dayjs`. ```js -dayjs().year(); +dayjs().year() ``` ### Mes `.month()` @@ -135,7 +135,7 @@ dayjs().year(); Devuelve un dato de tipo `number`, que representa el mes del objeto `Dayjs`. Se cuenta desde 0, que se corresponde con enero. ```js -dayjs().month(); +dayjs().month() ``` ### Día del mes `.date()` @@ -143,7 +143,7 @@ dayjs().month(); Devuelve un dato de tipo `number`, que indica el día del mes del objeto `Dayjs`. Empieza por el día 1. ```js -dayjs().date(); +dayjs().date() ``` ### Día de la semana `.day()` @@ -151,7 +151,7 @@ dayjs().date(); Devuelve un dato de tipo `number`, que indica el día de la semana del objeto `Dayjs`. Se cuenta desde 0, que se corresponde con el domingo. ```js -dayjs().day(); +dayjs().day() ``` ### Hora `.hour()` @@ -159,7 +159,7 @@ dayjs().day(); Devuelve un dato de tipo `number`, que indica la hora del objeto `Dayjs`. ```js -dayjs().hour(); +dayjs().hour() ``` ### Minuto `.minute()` @@ -167,7 +167,7 @@ dayjs().hour(); Devuelve un dato de tipo `number`, que indica los minutos del objeto `Dayjs`. ```js -dayjs().minute(); +dayjs().minute() ``` ### Segundo `.second()` @@ -175,7 +175,7 @@ dayjs().minute(); Devuelve un dato de tipo `number`, que indica los segundos del objeto `Dayjs`. ```js -dayjs().second(); +dayjs().second() ``` ### Milisegundo `.millisecond()` @@ -183,7 +183,7 @@ dayjs().second(); Devuelve un dato de tipo `number`, que indica los milisegundos del objeto `Dayjs`. ```js -dayjs().millisecond(); +dayjs().millisecond() ``` ### Set `.set(unit: string, value: number)` @@ -191,9 +191,9 @@ dayjs().millisecond(); Devuelve un nuevo objeto `Dayjs` con los cambios aplicados. ```js -dayjs().set("date", 1); -dayjs().set("month", 3); // Abril -dayjs().set("second", 30); +dayjs().set('date', 1) +dayjs().set('month', 3) // Abril +dayjs().set('second', 30) ``` #### Lista de unidades disponibles @@ -214,10 +214,10 @@ dayjs().set("second", 30); Los objetos `Dayjs` pueden manipularse de diversas formas. ```js -dayjs("2019-01-25") - .add(1, "day") - .subtract(1, "year") - .toString(); // Fri, 26 Jan 2018 00:00:00 GMT +dayjs('2019-01-25') + .add(1, 'day') + .subtract(1, 'year') + .toString() // Fri, 26 Jan 2018 00:00:00 GMT ``` ### Añadir `.add(value: number, unit: string)` @@ -225,7 +225,7 @@ dayjs("2019-01-25") Devuelve un nuevo objeto `Dayjs`, resultante de añadir al actual el tiempo indicado. ```js -dayjs().add(7, "day"); +dayjs().add(7, 'day') ``` ### Restar `.subtract(value: number, unit: string)` @@ -233,7 +233,7 @@ dayjs().add(7, "day"); Devuelve un nuevo objeto `Dayjs`, resultante de restar al actual el tiempo indicado. ```js -dayjs().subtract(7, "year"); +dayjs().subtract(7, 'year') ``` ### Principio de `.startOf(unit: string)` @@ -241,7 +241,7 @@ dayjs().subtract(7, "year"); Devuelve un nuevo objeto `Dayjs`, resultante de ajustar el actual al principio de la unidad de tiempo indicada. ```js -dayjs().startOf("week"); // Depends on `weekStart` in locale +dayjs().startOf('week') // Depends on `weekStart` in locale ``` ### Fin de `.endOf(unit: string)` @@ -249,7 +249,7 @@ dayjs().startOf("week"); // Depends on `weekStart` in locale Devuelve un nuevo objeto `Dayjs`, resultante de ajustar el actual al final de la unidad de tiempo indicada. ```js -dayjs().endOf("month"); +dayjs().endOf('month') ``` ## Presentación @@ -260,11 +260,11 @@ Devuelve un dato de tipo `string` con la fecha del objeto `Dayjs` formateada. Para escapar caracteres, estos se han de encerrar entre corchetes o llaves (p.ej.: `[G] {um}`). ```js -dayjs().format(); // fecha actual en ISO6801, sin fracciones de segundo p.ej. '2020-04-02T08:02:17-05:00' +dayjs().format() // fecha actual en ISO6801, sin fracciones de segundo p.ej. '2020-04-02T08:02:17-05:00' -dayjs("2019-01-25").format("{YYYY} MM-DDTHH:mm:ssZ[Z]"); // '{2019} 01-25T00:00:00-02:00Z' +dayjs('2019-01-25').format('{YYYY} MM-DDTHH:mm:ssZ[Z]') // '{2019} 01-25T00:00:00-02:00Z' -dayjs("2019-01-25").format("DD/MM/YYYY"); // '25/01/2019' +dayjs('2019-01-25').format('DD/MM/YYYY') // '25/01/2019' ``` #### Lista de formatos disponibles @@ -305,12 +305,12 @@ dayjs("2019-01-25").format("DD/MM/YYYY"); // '25/01/2019' Devuelve un dato de tipo `number`, que indica la diferencia existente entre dos objetos `Dayjs`, expresada en la unidad de tiempo dada. ```js -const date1 = dayjs("2019-01-25"); -const date2 = dayjs("2018-06-05"); -date1.diff(date2); // 20214000000 -date1.diff(date2, "month"); // 7 -date1.diff(date2, "month", true); // 7.645161290322581 -date1.diff(date2, "day"); // 233 +const date1 = dayjs('2019-01-25') +const date2 = dayjs('2018-06-05') +date1.diff(date2) // 20214000000 +date1.diff(date2, 'month') // 7 +date1.diff(date2, 'month', true) // 7.645161290322581 +date1.diff(date2, 'day') // 233 ``` ### Tiempo Unix (milisegundos) `.valueOf()` @@ -318,7 +318,7 @@ date1.diff(date2, "day"); // 233 Devuelve un dato de tipo `number`, que indica el número de milisegundos transcurridos desde la época Unix para el objeto `Dayjs`. ```js -dayjs("2019-01-25").valueOf(); // 1548381600000 +dayjs('2019-01-25').valueOf() // 1548381600000 ``` ### Tiempo Unix (segundos) `.unix()` @@ -326,7 +326,7 @@ dayjs("2019-01-25").valueOf(); // 1548381600000 Devuelve un dato de tipo `number`, que indica el número de segundos transcurridos desde la época Unix para el objeto `Dayjs`. ```js -dayjs("2019-01-25").unix(); // 1548381600 +dayjs('2019-01-25').unix() // 1548381600 ``` ### UTC Offset (minutos) `.utcOffset()` @@ -334,7 +334,7 @@ dayjs("2019-01-25").unix(); // 1548381600 Devuelve el UTC offset en minutos del `Dayjs`. ```js -dayjs().utcOffset(); +dayjs().utcOffset() ``` ### Días en el mes `.daysInMonth()` @@ -342,7 +342,7 @@ dayjs().utcOffset(); Devuelve un dato de tipo `number`, que indica el número de días contenidos en el mes del objeto `Dayjs`. ```js -dayjs("2019-01-25").daysInMonth(); // 31 +dayjs('2019-01-25').daysInMonth() // 31 ``` ### Como objeto `Date` `.toDate()` @@ -350,7 +350,7 @@ dayjs("2019-01-25").daysInMonth(); // 31 Devuelve un objeto `Date` nativo, obtenido a partir del objeto `Dayjs`. ```js -dayjs("2019-01-25").toDate(); +dayjs('2019-01-25').toDate() ``` ### Como array `.toArray()` @@ -358,7 +358,7 @@ dayjs("2019-01-25").toDate(); Devuelve un array que reproduce los parámetros de `new Date()`. ```js -dayjs("2019-01-25").toArray(); // [ 2019, 0, 25, 0, 0, 0, 0 ] +dayjs('2019-01-25').toArray() // [ 2019, 0, 25, 0, 0, 0, 0 ] ``` ### Como JSON `.toJSON()` @@ -366,7 +366,7 @@ dayjs("2019-01-25").toArray(); // [ 2019, 0, 25, 0, 0, 0, 0 ] Devuelve un objeto `Dayjs` formateado como una cadena ISO8601. ```js -dayjs("2019-01-25").toJSON(); // '2019-01-25T02:00:00.000Z' +dayjs('2019-01-25').toJSON() // '2019-01-25T02:00:00.000Z' ``` ### Como cadena ISO 8601 `.toISOString()` @@ -374,7 +374,7 @@ dayjs("2019-01-25").toJSON(); // '2019-01-25T02:00:00.000Z' Devuelve un objeto `Dayjs` formateado como una cadena ISO8601. ```js -dayjs("2019-01-25").toISOString(); // '2019-01-25T02:00:00.000Z' +dayjs('2019-01-25').toISOString() // '2019-01-25T02:00:00.000Z' ``` ### Como objecto `.toObject()` @@ -382,7 +382,7 @@ dayjs("2019-01-25").toISOString(); // '2019-01-25T02:00:00.000Z' Devuelve un dato de tipo `object`, con las propiedades de la fecha. ```js -dayjs("2019-01-25").toObject(); +dayjs('2019-01-25').toObject() /* { years: 2019, months: 0, date: 25, @@ -397,7 +397,7 @@ dayjs("2019-01-25").toObject(); Devuelve un dato de tipo `string`, que representa la fecha. ```js -dayjs("2019-01-25").toString(); // 'Fri, 25 Jan 2019 02:00:00 GMT' +dayjs('2019-01-25').toString() // 'Fri, 25 Jan 2019 02:00:00 GMT' ``` ## Consulta @@ -407,8 +407,8 @@ dayjs("2019-01-25").toString(); // 'Fri, 25 Jan 2019 02:00:00 GMT' Devuelve un dato de tipo `boolean`, que indica si la fecha del objeto `Dayjs` inicial es anterior o no a la fecha del objeto `Dayjs` a comparar. ```js -dayjs().isBefore(dayjs()); // false -dayjs().isBefore(dayjs(), "year"); // false +dayjs().isBefore(dayjs()) // false +dayjs().isBefore(dayjs(), 'year') // false ``` ### Igual que `.isSame(compared: Dayjs, unit?: string)` @@ -416,8 +416,8 @@ dayjs().isBefore(dayjs(), "year"); // false Devuelve un dato de tipo `boolean`, que indica si la fecha del objeto `Dayjs` inicial es igual o no que la fecha del objeto `Dayjs` a comparar. ```js -dayjs().isSame(dayjs()); // true -dayjs().isSame(dayjs(), "year"); // true +dayjs().isSame(dayjs()) // true +dayjs().isSame(dayjs(), 'year') // true ``` ### Posterior a `.isAfter(compared: Dayjs, unit?: string)` @@ -425,8 +425,8 @@ dayjs().isSame(dayjs(), "year"); // true Devuelve un dato de tipo `boolean`, que indica si la fecha del objeto `Dayjs` inicial es posterior o no a la fecha del objeto `Dayjs` a comparar. ```js -dayjs().isAfter(dayjs()); // false -dayjs().isAfter(dayjs(), "year"); // false +dayjs().isAfter(dayjs()) // false +dayjs().isAfter(dayjs(), 'year') // false ``` ### Es Dayjs `.isDayjs(compared: any)` @@ -434,14 +434,14 @@ dayjs().isAfter(dayjs(), "year"); // false Devuelve un dato de tipo `boolean`, que indica si la variable proporcionada es un objeto `Dayjs` o no. ```js -dayjs.isDayjs(dayjs()); // true -dayjs.isDayjs(new Date()); // false +dayjs.isDayjs(dayjs()) // true +dayjs.isDayjs(new Date()) // false ``` The operator `instanceof` works equally well: ```js -dayjs() instanceof dayjs; // true +dayjs() instanceof dayjs // true ``` ## API de complementos diff --git a/docs/es-es/I18n.md b/docs/es-es/I18n.md index c8de2810..30a950d5 100644 --- a/docs/es-es/I18n.md +++ b/docs/es-es/I18n.md @@ -16,7 +16,7 @@ Estás más que invitado a añadir otra configuración regional abriendo una pul ### Cambio de la configuración regional global -* Devuelve una cadena de configuración regional +- Devuelve una cadena de configuración regional ```js import 'dayjs/locale/es' @@ -31,23 +31,25 @@ dayjs.locale(customizedLocaleObject) dayjs.locale('en') // switch back to default English locale globally ``` -* Cambiar la configuración regional global no afecta a las instancias ya existentes. +- Cambiar la configuración regional global no afecta a las instancias ya existentes. #### Cambio local de configuraciones regionales -* Devuelve un nuevo objeto `Dayjs` con la nueva configuración regional. +- Devuelve un nuevo objeto `Dayjs` con la nueva configuración regional. Se usa igual que `dayjs#locale`, con la salvedad de que se utiliza `locale` sobre una instancia específica. ```js import 'dayjs/locale/es' -dayjs().locale('es').format() // uso local de la configuración regional cargada +dayjs() + .locale('es') + .format() // uso local de la configuración regional cargada dayjs('2018-4-28', { locale: es }) // ídem, pero mediante el constructor ``` ## Instalación -* Vía NPM: +- Vía NPM: ```javascript import 'dayjs/locale/es' // carga bajo demanda @@ -56,18 +58,22 @@ import 'dayjs/locale/es' // carga bajo demanda dayjs.locale('es') // uso global de la configuración regional // uso de la configuración regional en una instancia específica -dayjs().locale('es').format() +dayjs() + .locale('es') + .format() ``` -* Vía CDN: +- Vía CDN: ```html @@ -80,6 +86,7 @@ You could create your own locale. Feel free to open a pull request to share your locale. Template of a Day.js locale Object. + ```javascript const localeObject = { name: 'es', // name String @@ -89,7 +96,8 @@ const localeObject = { months: 'Enero_Febrero ... '.split('_'), // months Array monthsShort: 'Jan_F'.split('_'), // OPTIONAL, short months Array, use first three letters if not provided ordinal: n => `${n}º`, // ordinal Function (number) => return number + output - relativeTime: { // relative time format strings, keep %s %d as the same + relativeTime: { + // relative time format strings, keep %s %d as the same future: 'in %s', // e.g. in 2 hours, %s been replaced with 2hours past: '%s ago', s: 'a few seconds', @@ -108,6 +116,7 @@ const localeObject = { ``` Template of a Day.js locale file. + ```javascript import dayjs from 'dayjs' diff --git a/docs/es-es/Installation.md b/docs/es-es/Installation.md index 0a93489b..cebdf626 100644 --- a/docs/es-es/Installation.md +++ b/docs/es-es/Installation.md @@ -2,7 +2,7 @@ Tienes a tu disposición varias opciones para obtener y utilizar Day.js: -* Vía NPM: +- Vía NPM: ```console npm install dayjs --save @@ -12,19 +12,19 @@ npm install dayjs --save import dayjs from 'dayjs' // O con CommonJS // var dayjs = require('dayjs'); -dayjs().format(); +dayjs().format() ``` -* Vía CDN: +- Vía CDN: ```html ``` -* Vía descarga directa y autohospedaje: +- Vía descarga directa y autohospedaje: -Simplemente descarga la última versión de Day.js en [https://unpkg.com/dayjs/](https://unpkg.com/dayjs/). \ No newline at end of file +Simplemente descarga la última versión de Day.js en [https://unpkg.com/dayjs/](https://unpkg.com/dayjs/). diff --git a/docs/es-es/Plugin.md b/docs/es-es/Plugin.md index 941b3ff3..aede05fd 100644 --- a/docs/es-es/Plugin.md +++ b/docs/es-es/Plugin.md @@ -25,10 +25,10 @@ dayjs.extend(nombreComplemento, options) // uso del complemento con opciones - Vía NPM: ```javascript -import dayjs from "dayjs"; -import AdvancedFormat from "dayjs/plugin/advancedFormat"; // carga bajo demanda +import dayjs from 'dayjs' +import AdvancedFormat from 'dayjs/plugin/advancedFormat' // carga bajo demanda -dayjs.extend(AdvancedFormat); // uso del complemento +dayjs.extend(AdvancedFormat) // uso del complemento ``` - Vía CDN: @@ -38,7 +38,7 @@ dayjs.extend(AdvancedFormat); // uso del complemento ``` @@ -49,11 +49,11 @@ dayjs.extend(AdvancedFormat); // uso del complemento - AdvancedFormat extiende la API `dayjs().format` para proporcionar más opciones de formato. ```javascript -import advancedFormat from "dayjs/plugin/advancedFormat"; +import advancedFormat from 'dayjs/plugin/advancedFormat' -dayjs.extend(advancedFormat); +dayjs.extend(advancedFormat) -dayjs().format("Q Do k kk X x"); +dayjs().format('Q Do k kk X x') ``` Lista de formatos añadidos: @@ -68,7 +68,8 @@ Lista de formatos añadidos: | `x` | 1360013296123 | Tiempo Unix en milisegundos | ### LocalizedFormat - - LocalizedFormat extends `dayjs().format` API to supply localized format options. + +- LocalizedFormat extends `dayjs().format` API to supply localized format options. ```javascript import LocalizedFormat from 'dayjs/plugin/localizedFormat' @@ -94,18 +95,18 @@ List of added formats: - RelativeTime añade las API `.from` `.to` `.fromNow` `.toNow` para dar formato de tiempo relativo a fechas (p.ej.: hace 3 horas). ```javascript -import relativeTime from "dayjs/plugin/relativeTime"; +import relativeTime from 'dayjs/plugin/relativeTime' -dayjs.extend(relativeTime); +dayjs.extend(relativeTime) -dayjs().from(dayjs("1990")); // hace 2 años -dayjs().from(dayjs(), true); // 2 años +dayjs().from(dayjs('1990')) // hace 2 años +dayjs().from(dayjs(), true) // 2 años -dayjs().fromNow(); +dayjs().fromNow() -dayjs().to(dayjs()); +dayjs().to(dayjs()) -dayjs().toNow(); +dayjs().toNow() ``` #### Tiempo desde ahora `.fromNow(withoutSuffix?: boolean)` @@ -143,11 +144,11 @@ Devuelve dato de tipo `string`, con el tiempo relativo transcurrido desde la fec - IsLeapYear añade la API `.isLeapYear`, que devuelve un dato de tipo `boolean` indicando si el año del objeto `Dayjs` es bisiesto o no. ```javascript -import isLeapYear from "dayjs/plugin/isLeapYear"; +import isLeapYear from 'dayjs/plugin/isLeapYear' -dayjs.extend(isLeapYear); +dayjs.extend(isLeapYear) -dayjs("2000-01-01").isLeapYear(); // true +dayjs('2000-01-01').isLeapYear() // true ``` ### BuddhistEra @@ -157,11 +158,11 @@ dayjs("2000-01-01").isLeapYear(); // true - Para calcular manualmente el año de la BE tan sólo hemos de sumar 543 al año. Por ejemplo, el 26 Mayo 1977 AD/EC debe mostrarse como 26 Mayo 2520 BE (1977 + 543) ```javascript -import buddhistEra from "dayjs/plugin/buddhistEra"; +import buddhistEra from 'dayjs/plugin/buddhistEra' -dayjs.extend(buddhistEra); +dayjs.extend(buddhistEra) -dayjs().format("BBBB BB"); +dayjs().format('BBBB BB') ``` Lista de formatos añadidos: @@ -176,11 +177,11 @@ Lista de formatos añadidos: - IsSameOrAfter adds `.isSameOrAfter()` API to returns a `boolean` indicating if a date is same of after another date. ```javascript -import isSameOrAfter from "dayjs/plugin/isSameOrAfter"; +import isSameOrAfter from 'dayjs/plugin/isSameOrAfter' -dayjs.extend(isSameOrAfter); +dayjs.extend(isSameOrAfter) -dayjs("2010-10-20").isSameOrAfter("2010-10-19", "year"); +dayjs('2010-10-20').isSameOrAfter('2010-10-19', 'year') ``` ### IsSameOrBefore @@ -188,11 +189,11 @@ dayjs("2010-10-20").isSameOrAfter("2010-10-19", "year"); - IsSameOrBefore adds `.isSameOrBefore()` API to returns a `boolean` indicating if a date is same of before another date. ```javascript -import isSameOrBefore from "dayjs/plugin/isSameOrBefore"; +import isSameOrBefore from 'dayjs/plugin/isSameOrBefore' -dayjs.extend(isSameOrBefore); +dayjs.extend(isSameOrBefore) -dayjs("2010-10-20").isSameOrBefore("2010-10-19", "year"); +dayjs('2010-10-20').isSameOrBefore('2010-10-19', 'year') ``` ### IsBetween @@ -200,12 +201,12 @@ dayjs("2010-10-20").isSameOrBefore("2010-10-19", "year"); - IsBetween añade la API `.isBetween()`, que devuelve un dato de tipo `boolean` indicando si una fecha se encuentra o no entre otras dos dadas. ```javascript -import isBetween from "dayjs/plugin/isBetween"; +import isBetween from 'dayjs/plugin/isBetween' -dayjs.extend(isBetween); +dayjs.extend(isBetween) -dayjs("2010-10-20").isBetween("2010-10-19", dayjs("2010-10-25"), "year"); -dayjs('2016-10-30').isBetween('2016-01-01', '2016-10-30', null, '[)'); +dayjs('2010-10-20').isBetween('2010-10-19', dayjs('2010-10-25'), 'year') +dayjs('2016-10-30').isBetween('2016-01-01', '2016-10-30', null, '[)') // '[' indicates inclusion, '(' indicates exclusion ``` @@ -214,12 +215,12 @@ dayjs('2016-10-30').isBetween('2016-01-01', '2016-10-30', null, '[)'); - DayOfYear añade a la API `.dayOfYear()`, que devuelve un dato de tipo `number` indicando el día del año correspondiente a la fecha del objeto `Dayjs`, or to set the day of the year. ```javascript -import dayOfYear from "dayjs/plugin/dayOfYear"; +import dayOfYear from 'dayjs/plugin/dayOfYear' -dayjs.extend(dayOfYear); +dayjs.extend(dayOfYear) -dayjs("2018-01-01").week(); // 1 -dayjs("2010-01-01").dayOfYear(365); // 2010-12-31 +dayjs('2018-01-01').week() // 1 +dayjs('2010-01-01').dayOfYear(365) // 2010-12-31 ``` ### WeekOfYear @@ -227,11 +228,11 @@ dayjs("2010-01-01").dayOfYear(365); // 2010-12-31 - WeekOfYear añade la API `.week()`, que devuelve un dato de tipo `number` indicando la semana del año correspondiente a la fecha del objeto `Dayjs`. ```javascript -import weekOfYear from "dayjs/plugin/weekOfYear"; +import weekOfYear from 'dayjs/plugin/weekOfYear' -dayjs.extend(weekOfYear); +dayjs.extend(weekOfYear) -dayjs("2018-06-27").week(); // 26 +dayjs('2018-06-27').week() // 26 ``` ### QuarterOfYear @@ -239,11 +240,11 @@ dayjs("2018-06-27").week(); // 26 - QuarterOfYear añade a la API `.quarter()` para devolver a que cuarto del año pertenece una fecha ```javascript -import quarterOfYear from "dayjs/plugin/quarterOfYear"; +import quarterOfYear from 'dayjs/plugin/quarterOfYear' -dayjs.extend(quarterOfYear); +dayjs.extend(quarterOfYear) -dayjs("2010-04-01").quarter(); // 2 +dayjs('2010-04-01').quarter() // 2 ``` #### List of all available format tokens @@ -284,19 +285,19 @@ Plantilla de un complemento de Day.js. export default (option, dayjsClass, dayjsFactory) => { // extensión de dayjs() // p.ej.: se añade dayjs().isSameOrBefore() - dayjsClass.prototype.isSameOrBefore = function(arguments) {}; + dayjsClass.prototype.isSameOrBefore = function(arguments) {} // extensión de dayjs // p.ej.: se añade dayjs.utc() - dayjsFactory.utc = arguments => {}; + dayjsFactory.utc = arguments => {} // sobrescritura de la API existente // p.ej.: extensión de dayjs().format() - const oldFormat = dayjsClass.prototype.format; + const oldFormat = dayjsClass.prototype.format dayjsClass.prototype.format = function(arguments) { // result contiene el formato original - const result = oldFormat(arguments); + const result = oldFormat(arguments) // se ha de devolver result modificado - }; -}; + } +} ``` diff --git a/docs/es-es/README-es-es.md b/docs/es-es/README-es-es.md index 7172189b..7e7d6bc8 100644 --- a/docs/es-es/README-es-es.md +++ b/docs/es-es/README-es-es.md @@ -24,15 +24,19 @@ > Day.js es una librería JavaScript minimalista que analiza, valida, manipula y muestra fechas y horas para navegadores modernos, manteniendo una API casi totalmente compatible con Moment.js. Si usas Moment.js, ya sabes usar Day.js. ```js -dayjs().startOf('month').add(1, 'day').set('year', 2018).format('YYYY-MM-DD HH:mm:ss'); +dayjs() + .startOf('month') + .add(1, 'day') + .set('year', 2018) + .format('YYYY-MM-DD HH:mm:ss') ``` -* 🕒 API & patrones familiares para usuarios de Moment.js -* 💪 Inmutable -* 🔥 Encadenable -* 🌐 Soporta I18n -* 📦 Mini librería de 2kb -* 👫 Compatible con todos los navegadores +- 🕒 API & patrones familiares para usuarios de Moment.js +- 💪 Inmutable +- 🔥 Encadenable +- 🌐 Soporta I18n +- 📦 Mini librería de 2kb +- 👫 Compatible con todos los navegadores --- @@ -55,7 +59,9 @@ dayjs('2018-08-08') // analiza dayjs().format('{YYYY} MM-DDTHH:mm:ss SSS [Z] A') // da formato -dayjs().set('month', 3).month() // get & set +dayjs() + .set('month', 3) + .month() // get & set dayjs().add(1, 'year') // manipula @@ -75,14 +81,16 @@ import 'dayjs/locale/es' // carga bajo demanda dayjs.locale('es') // usar la configuración regional española globalmente -dayjs('2018-05-05').locale('zh-cn').format() // usar el chino simplificado en una instancia concreta +dayjs('2018-05-05') + .locale('zh-cn') + .format() // usar el chino simplificado en una instancia concreta ``` 📚[Internacionalización](./I18n.md) ## Complementos -Un complemento o *plugin* es un módulo independiente que puede añadirse a Day.js para extender su funcionalidad o añadir nuevas características. +Un complemento o _plugin_ es un módulo independiente que puede añadirse a Day.js para extender su funcionalidad o añadir nuevas características. ```javascript import advancedFormat from 'dayjs/plugin/advancedFormat' // carga bajo demanda diff --git a/docs/ja/API-reference.md b/docs/ja/API-reference.md index 9735c7a5..bad37952 100644 --- a/docs/ja/API-reference.md +++ b/docs/ja/API-reference.md @@ -4,56 +4,56 @@ Day.js は組み込みの `Date.prototype` を変更する代わりに `Dayjs` `Dayjs` オブジェクトは不変 (immutable) です。すなわち、すべての API 操作は新しい `Dayjs` オブジェクトを返します。 -* [Parse](#parse) - * [Now](#now) - * [String](#string) - * [Date](#date) - * [Unix Timestamp (milliseconds)](#unix-timestamp-milliseconds) - * [Unix Timestamp (seconds)](#unix-timestamp-seconds) - * [Custom Parse Format](#custom-parse-format) - * [Clone](#clone) - * [Validation](#validation) -* [Get + Set](#get--set) - * [Year](#year) - * [Month](#month) - * [Date of Month](#date-of-month) - * [Day of Week](#day-of-week) - * [Hour](#hour) - * [Minute](#minute) - * [Second](#second) - * [Millisecond](#millisecond) - * [Set](#set) -* [Manipulate](#manipulate) - * [Add](#add) - * [Subtract](#subtract) - * [Start of Time](#start-of-time) - * [End of Time](#end-of-time) -* [Display](#display) - * [Format](#format) - * [Difference](#difference) - * [Unix Timestamp (milliseconds)](#unix-timestamp-milliseconds-1) - * [Unix Timestamp (seconds)](#unix-timestamp-seconds) - * [UTC offset (minutes)](#utc-offset-minutes-utcoffset) - * [Days in Month](#days-in-month) - * [As Javascript Date](#as-javascript-date) - * [As Array](#as-array) - * [As JSON](#as-json) - * [As ISO 8601 String](#as-iso-8601-string) - * [As Object](#as-object) - * [As String](#as-string) -* [Query](#query) - * [Is Before](#is-before) - * [Is Same](#is-same) - * [Is After](#is-after) - * [Is a Dayjs](#is-a-dayjs) -* [Plugin APIs](#plugin-apis) - * [RelativeTime](#relativetime) - * [IsLeapYear](#isleapyear) - * [WeekOfYear](#weekofyear) - * [IsSameOrAfter](#issameorafter) - * [IsSameOrBefore](#issameorbefore) - * [IsBetween](#isbetween) - * [QuarterOfYear](#quarterofyear) +- [Parse](#parse) + - [Now](#now) + - [String](#string) + - [Date](#date) + - [Unix Timestamp (milliseconds)](#unix-timestamp-milliseconds) + - [Unix Timestamp (seconds)](#unix-timestamp-seconds) + - [Custom Parse Format](#custom-parse-format) + - [Clone](#clone) + - [Validation](#validation) +- [Get + Set](#get--set) + - [Year](#year) + - [Month](#month) + - [Date of Month](#date-of-month) + - [Day of Week](#day-of-week) + - [Hour](#hour) + - [Minute](#minute) + - [Second](#second) + - [Millisecond](#millisecond) + - [Set](#set) +- [Manipulate](#manipulate) + - [Add](#add) + - [Subtract](#subtract) + - [Start of Time](#start-of-time) + - [End of Time](#end-of-time) +- [Display](#display) + - [Format](#format) + - [Difference](#difference) + - [Unix Timestamp (milliseconds)](#unix-timestamp-milliseconds-1) + - [Unix Timestamp (seconds)](#unix-timestamp-seconds) + - [UTC offset (minutes)](#utc-offset-minutes-utcoffset) + - [Days in Month](#days-in-month) + - [As Javascript Date](#as-javascript-date) + - [As Array](#as-array) + - [As JSON](#as-json) + - [As ISO 8601 String](#as-iso-8601-string) + - [As Object](#as-object) + - [As String](#as-string) +- [Query](#query) + - [Is Before](#is-before) + - [Is Same](#is-same) + - [Is After](#is-after) + - [Is a Dayjs](#is-a-dayjs) +- [Plugin APIs](#plugin-apis) + - [RelativeTime](#relativetime) + - [IsLeapYear](#isleapyear) + - [WeekOfYear](#weekofyear) + - [IsSameOrAfter](#issameorafter) + - [IsSameOrBefore](#issameorbefore) + - [IsBetween](#isbetween) + - [QuarterOfYear](#quarterofyear) --- @@ -68,7 +68,7 @@ Day.js は指定されない限り、常に新しい Dayjs オブジェクトを 現在の日付と時間を取得するには、パラメータなしで dayjs() を呼び出します。 ```js -dayjs(); +dayjs() ``` ### String @@ -76,8 +76,8 @@ dayjs(); [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) に準拠する形式から作成します。 ```js -dayjs(String); -dayjs('1995-12-25'); +dayjs(String) +dayjs('1995-12-25') ``` ### Date @@ -85,28 +85,29 @@ dayjs('1995-12-25'); JavaScript の組み込みの Date オブジェクトを渡します。 ```js -dayjs(Date); -dayjs(new Date(2018, 8, 18)); +dayjs(Date) +dayjs(new Date(2018, 8, 18)) ``` ### Unix Timestamp (milliseconds) -Unix エポック (1970年1月1日 12:00AM UTC) 以降のミリ秒数を表す整数値を渡します。 +Unix エポック (1970 年 1 月 1 日 12:00AM UTC) 以降のミリ秒数を表す整数値を渡します。 ```js -dayjs(Number); -dayjs(1318781876406); +dayjs(Number) +dayjs(1318781876406) ``` ### Unix Timestamp (seconds) ```js -dayjs.unix(Number); -dayjs.unix(1318781876); +dayjs.unix(Number) +dayjs.unix(1318781876) ``` ### Custom Parse Format -* parse custom formats `dayjs("12-25-1995", "MM-DD-YYYY")` in plugin [`CustomParseFormat`](./Plugin.md#customparseformat) + +- parse custom formats `dayjs("12-25-1995", "MM-DD-YYYY")` in plugin [`CustomParseFormat`](./Plugin.md#customparseformat) ### Clone @@ -114,18 +115,18 @@ dayjs.unix(1318781876); `Dayjs` オブジェクトに対して dayjs() を呼び出すと、それもクローンされます。 ```js -dayjs(Dayjs); -dayjs().clone(); +dayjs(Dayjs) +dayjs().clone() ``` ### Validation -* Boolean を返します +- Boolean を返します `Dayjs` オブジェクトが有効な日付かどうかをチェックします。 ```js -dayjs().isValid(); +dayjs().isValid() ``` --- @@ -136,82 +137,82 @@ dayjs().isValid(); #### Year -* Number を返します +- Number を返します 年を取得します。 ```js -dayjs().year(); +dayjs().year() ``` #### Month -* Number を返します +- Number を返します 月を取得します。 ```js -dayjs().month(); +dayjs().month() ``` #### Date of Month -* Number を返します +- Number を返します 日を取得します。 ```js -dayjs().date(); +dayjs().date() ``` #### Day of Week -* Number を返します +- Number を返します 曜日を取得します。 ```js -dayjs().day(); +dayjs().day() ``` #### Hour -* Number を返します +- Number を返します 時間を取得します。 ```js -dayjs().hour(); +dayjs().hour() ``` #### Minute -* Number を返します +- Number を返します 分を取得します。 ```js -dayjs().minute(); +dayjs().minute() ``` #### Second -* Number を返します +- Number を返します 秒を取得します。 ```js -dayjs().second(); +dayjs().second() ``` #### Millisecond -* Number を返します +- Number を返します ミリ秒を取得します。 ```js -dayjs().millisecond(); +dayjs().millisecond() ``` #### Set @@ -220,10 +221,10 @@ dayjs().millisecond(); 単位は大文字・小文字を区別しません。 ```js -dayjs().set((unit: String), (value: Int)); -dayjs().set('date', 1); -dayjs().set('month', 3); // 4月 -dayjs().set('second', 30); +dayjs().set((unit: String), (value: Int)) +dayjs().set('date', 1) +dayjs().set('month', 3) // 4月 +dayjs().set('second', 30) ``` #### List of all available units @@ -249,7 +250,7 @@ dayjs().set('second', 30); dayjs() .startOf('month') .add(1, 'day') - .subtract(1, 'year'); + .subtract(1, 'year') ``` #### Add @@ -257,8 +258,8 @@ dayjs() 時間を足して新しい `Dayjs` オブジェクトを返します。 ```js -dayjs().add((value: Number), (unit: String)); -dayjs().add(7, 'day'); +dayjs().add((value: Number), (unit: String)) +dayjs().add(7, 'day') ``` #### Subtract @@ -266,8 +267,8 @@ dayjs().add(7, 'day'); 時間を引いて新しい `Dayjs` オブジェクトを返します。 `dayjs#add` と全く同じです。 ```js -dayjs().subtract((value: Number), (unit: String)); -dayjs().subtract(7, 'year'); +dayjs().subtract((value: Number), (unit: String)) +dayjs().subtract(7, 'year') ``` #### Start of Time @@ -277,8 +278,8 @@ Returns a new `Dayjs` object by by setting it to the start of a unit of time. ある単位の始まりの時間の新しい `Dayjs` オブジェクトを返します。 ```js -dayjs().startOf((unit: String)); -dayjs().startOf('week'); // Depends on `weekStart` in locale +dayjs().startOf((unit: String)) +dayjs().startOf('week') // Depends on `weekStart` in locale ``` #### End of Time @@ -286,8 +287,8 @@ dayjs().startOf('week'); // Depends on `weekStart` in locale ある単位の終わりの時間の新しい `Dayjs` オブジェクトを返します。 ```js -dayjs().endOf((unit: String)); -dayjs().endOf('month'); +dayjs().endOf((unit: String)) +dayjs().endOf('month') ``` --- @@ -298,84 +299,84 @@ dayjs().endOf('month'); #### Format -* String を返します +- String を返します 文字列を受け取り、対応する日付の値で置き換えます。 ```js -dayjs().format(String); -dayjs().format(); // "2014-09-08T08:02:17-05:00" (ISO 8601 形式、小数部は含まない) -dayjs().format('{YYYY} MM-DDTHH:mm:ssZ[Z]'); // "{2014} 09-08T08:02:17-05:00Z" +dayjs().format(String) +dayjs().format() // "2014-09-08T08:02:17-05:00" (ISO 8601 形式、小数部は含まない) +dayjs().format('{YYYY} MM-DDTHH:mm:ssZ[Z]') // "{2014} 09-08T08:02:17-05:00Z" ``` -* 文字列内の文字をエスケープするには、文字を角括弧で囲みます (例: [Z]) 。 +- 文字列内の文字をエスケープするには、文字を角括弧で囲みます (例: [Z]) 。 使用可能なフォーマットの一覧: -| フォーマット | 出力 | 説明 | -| ------ | ---------------- | ------------------------------------- | -| `YY` | 18 | 2桁の年 | -| `YYYY` | 2018 | 4桁の年 | -| `M` | 1-12 | 1始まりの月 | -| `MM` | 01-12 | 1始まりかつ2桁の月 | -| `MMM` | Jan-Dec | 月の略称 | -| `MMMM` | January-December | 月の正式名 | -| `D` | 1-31 | 日 | -| `DD` | 01-31 | 2桁の日 | -| `d` | 0-6 | 曜日 (日曜は0) | -| `dd` | Su-Sa | 最も短い曜日の略称 | -| `ddd` | Sun-Sat | 曜日の略称 | -| `dddd` | Sunday-Saturday | 曜日名 | -| `H` | 0-23 | 時間 | -| `HH` | 00-23 | 2桁の時間 | -| `h` | 1-12 | 12時制の時間 | -| `hh` | 01-12 | 12時制かつ2桁の時間 | -| `m` | 0-59 | 分 | -| `mm` | 00-59 | 2桁の分 | -| `s` | 0-59 | 秒 | -| `ss` | 00-59 | 2桁の秒 | -| `SSS` | 000-999 | 3桁のミリ秒 | -| `Z` | +5:00 | UTC からのオフセット | -| `ZZ` | +0500 | UTC からの2桁のオフセット | -| `A` | AM PM | 午前と午後 (大文字) | -| `a` | am pm | 午前と午後 (小文字) | +| フォーマット | 出力 | 説明 | +| ------------ | ---------------- | --------------------------- | +| `YY` | 18 | 2 桁の年 | +| `YYYY` | 2018 | 4 桁の年 | +| `M` | 1-12 | 1 始まりの月 | +| `MM` | 01-12 | 1 始まりかつ 2 桁の月 | +| `MMM` | Jan-Dec | 月の略称 | +| `MMMM` | January-December | 月の正式名 | +| `D` | 1-31 | 日 | +| `DD` | 01-31 | 2 桁の日 | +| `d` | 0-6 | 曜日 (日曜は 0) | +| `dd` | Su-Sa | 最も短い曜日の略称 | +| `ddd` | Sun-Sat | 曜日の略称 | +| `dddd` | Sunday-Saturday | 曜日名 | +| `H` | 0-23 | 時間 | +| `HH` | 00-23 | 2 桁の時間 | +| `h` | 1-12 | 12 時制の時間 | +| `hh` | 01-12 | 12 時制かつ 2 桁の時間 | +| `m` | 0-59 | 分 | +| `mm` | 00-59 | 2 桁の分 | +| `s` | 0-59 | 秒 | +| `ss` | 00-59 | 2 桁の秒 | +| `SSS` | 000-999 | 3 桁のミリ秒 | +| `Z` | +5:00 | UTC からのオフセット | +| `ZZ` | +0500 | UTC からの 2 桁のオフセット | +| `A` | AM PM | 午前と午後 (大文字) | +| `a` | am pm | 午前と午後 (小文字) | - plugin [`AdvancedFormat`](./Plugin.md#advancedformat) にはより多くのフォーマット(例: `Q Do k kk X x ...` )が存在します。 - Localized format options `L LT LTS ...` in plugin [`LocalizedFormat`](./Plugin.md#localizedFormat) #### Difference -* Number を返します +- Number を返します -2つの `Dayjs` オブジェクトの差をミリ秒単位で取得します。 +2 つの `Dayjs` オブジェクトの差をミリ秒単位で取得します。 ```js -const date1 = dayjs('2019-01-25'); -const date2 = dayjs('2018-06-05'); -date1.diff(date2); // 20214000000 -date1.diff(date2, 'month'); // 7 -date1.diff(date2, 'month', true); // 7.645161290322581 -date1.diff(date2, 'day'); // 233 +const date1 = dayjs('2019-01-25') +const date2 = dayjs('2018-06-05') +date1.diff(date2) // 20214000000 +date1.diff(date2, 'month') // 7 +date1.diff(date2, 'month', true) // 7.645161290322581 +date1.diff(date2, 'day') // 233 ``` #### Unix Timestamp (milliseconds) -* Number を返します +- Number を返します Unix エポックからのミリ秒数を出力します。 ```js -dayjs().valueOf(); +dayjs().valueOf() ``` #### Unix Timestamp (seconds) -* Number を返します +- Number を返します Unix タイムスタンプ (Unix エポックからの秒数) を出力します。 ```js -dayjs().unix(); +dayjs().unix() ``` ### UTC Offset (minutes) @@ -383,76 +384,75 @@ dayjs().unix(); Returns the UTC offset in minutes for the `Dayjs`. ```js -dayjs().utcOffset(); +dayjs().utcOffset() ``` #### Days in Month -* Number を返します +- Number を返します その月の日数を取得します。 ```js -dayjs().daysInMonth(); +dayjs().daysInMonth() ``` #### As Javascript Date -* Javascript の `Date` オブジェクトを返します +- Javascript の `Date` オブジェクトを返します `Dayjs` オブジェクトから組み込みの `Date` オブジェクトのコピーを取得します。 ```js -dayjs().toDate(); +dayjs().toDate() ``` #### As Array -* Array を返します +- Array を返します Date コンストラクタパラメータに対応する値の配列を返します。 ```js -dayjs().toArray(); //[2018, 8, 18, 00, 00, 00, 000]; +dayjs().toArray() //[2018, 8, 18, 00, 00, 00, 000]; ``` #### As JSON -* JSON String を返します +- JSON String を返します `Dayjs` オブジェクトを JSON シリアライズし、ISO8601 形式の日付文字列を返します。 ```js -dayjs().toJSON(); //"2018-08-08T00:00:00.000Z" +dayjs().toJSON() //"2018-08-08T00:00:00.000Z" ``` #### As ISO 8601 String -* String を返します +- String を返します ISO8601 形式の文字列にフォーマットします。 ```js -dayjs().toISOString(); +dayjs().toISOString() ``` #### As Object -* Object を返します +- Object を返します 年、月、...(中略)...、ミリ秒のオブジェクトを返します。 - ```js -dayjs().toObject(); // { years:2018, months:8, date:18, hours:0, minutes:0, seconds:0, milliseconds:0} +dayjs().toObject() // { years:2018, months:8, date:18, hours:0, minutes:0, seconds:0, milliseconds:0} ``` #### As String -* String を返します +- String を返します ```js -dayjs().toString(); +dayjs().toString() ``` --- @@ -461,7 +461,7 @@ dayjs().toString(); #### Is Before -* Boolean を返します +- Boolean を返します `Dayjs` オブジェクトが別の `Dayjs` オブジェクト以前の値かどうかを判定します。 @@ -473,7 +473,7 @@ dayjs().isBefore(dayjs(), 'year'); // false #### Is Same -* Boolean を返します +- Boolean を返します `Dayjs` オブジェクトが別の `Dayjs` オブジェクトの値と等しいかどうかを判定します。 @@ -485,7 +485,7 @@ dayjs().isSame(dayjs(), 'year'); // true #### Is After -* Boolean を返します +- Boolean を返します `Dayjs` オブジェクトが別の `Dayjs` オブジェクト以降の値かどうかを判定します。 @@ -497,7 +497,7 @@ dayjs().isAfter(dayjs(), 'year'); // false #### Is a Dayjs -* Boolean を返します +- Boolean を返します 与えられた値が `Dayjs` オブジェクトであるかどうかを判定します。 @@ -547,7 +547,7 @@ plugin [`IsSameOrBefore`](./Plugin.md#issameorbefore) #### IsBetween -`.isBetween` はある日付が別の2つの日付の間にあるかどうかを判定します。 +`.isBetween` はある日付が別の 2 つの日付の間にあるかどうかを判定します。 plugin [`IsBetween`](./Plugin.md#isbetween) diff --git a/docs/ja/I18n.md b/docs/ja/I18n.md index 8f853b8e..a53e646d 100644 --- a/docs/ja/I18n.md +++ b/docs/ja/I18n.md @@ -16,7 +16,7 @@ pull request によるロケールの追加は大歓迎です。 :+1: #### グローバルロケールの変更 -* ロケール文字列を返します +- ロケール文字列を返します ```js import 'dayjs/locale/es' @@ -28,23 +28,25 @@ dayjs.locale(customizedLocaleObject) // カスタムロケールを適用 dayjs.locale('en') // switch back to default English locale globally ``` -* グローバルロケールを変更しても、既存のインスタンスには影響しません。 +- グローバルロケールを変更しても、既存のインスタンスには影響しません。 #### 局所的なロケールの変更 -* 指定したロケールを適用した、新しい `Dayjs` オブジェクトを返します +- 指定したロケールを適用した、新しい `Dayjs` オブジェクトを返します `dayjs#locale` と同じですが、特定のインスタンスにのみロケールを適用します。 ```js import 'dayjs/locale/es' -dayjs().locale('es').format() // 読み込んだロケールを特定のインスタンスに適用 +dayjs() + .locale('es') + .format() // 読み込んだロケールを特定のインスタンスに適用 dayjs('2018-4-28', { locale: 'es' }) // コンストラクタを通して適用 ``` ## インストール -* NPM を使う場合: +- NPM を使う場合: ```javascript import 'dayjs/locale/es' // 必要に応じて読み込み @@ -52,18 +54,22 @@ import 'dayjs/locale/es' // 必要に応じて読み込み // import locale_es from 'dayjs/locale/es' -> locale_es ロケールオブジェクトの読み込み dayjs.locale('es') // ロケールをグローバルに適用 -dayjs().locale('es').format() // ロケールを特定のインスタンスにのみ適用 +dayjs() + .locale('es') + .format() // ロケールを特定のインスタンスにのみ適用 ``` -* CDN を使う場合: +- CDN を使う場合: ```html @@ -87,7 +93,8 @@ const localeObject = { months: 'Enero_Febrero ... '.split('_'), // 月の配列 monthsShort: 'Jan_F'.split('_'), // OPTIONAL, short months Array, use first three letters if not provided ordinal: n => `${n}º`, // 序数 Function (number) => return number + output - relativeTime: { // relative time format strings, keep %s %d as the same + relativeTime: { + // relative time format strings, keep %s %d as the same future: 'in %s', // e.g. in 2 hours, %s been replaced with 2hours past: '%s ago', s: 'a few seconds', diff --git a/docs/ja/Installation.md b/docs/ja/Installation.md index b71cfe1b..a2e6055f 100644 --- a/docs/ja/Installation.md +++ b/docs/ja/Installation.md @@ -2,7 +2,7 @@ 複数の方法で Day.js を使用することができます -* NPM を使う場合: +- NPM を使う場合: ```console npm install dayjs --save @@ -12,19 +12,19 @@ npm install dayjs --save import dayjs from 'dayjs' // CommonJS の場合は以下 // var dayjs = require('dayjs'); -dayjs().format(); +dayjs().format() ``` -* CDN を使う場合: +- CDN を使う場合: ```html ``` -* ダウンロードしてセルフホスティングする場合: +- ダウンロードしてセルフホスティングする場合: Day.js の最新版を [https://unpkg.com/dayjs/](https://unpkg.com/dayjs/) からダウンロードしてください。 diff --git a/docs/ja/Plugin.md b/docs/ja/Plugin.md index a9ba2e99..4be8f2e4 100644 --- a/docs/ja/Plugin.md +++ b/docs/ja/Plugin.md @@ -10,7 +10,7 @@ #### 拡張 -* dayjs オブジェクトを返します +- dayjs オブジェクトを返します プラグインの使用例です。 @@ -22,7 +22,7 @@ dayjs.extend(plugin, options) // プラグインのオプションを指定 ## インストール -* NPM を使う場合: +- NPM を使う場合: ```javascript import dayjs from 'dayjs' @@ -31,21 +31,22 @@ import advancedFormat from 'dayjs/plugin/advancedFormat' // 必要に応じて dayjs.extend(advancedFormat) // プラグインを使用 ``` -* CDN を使う場合: +- CDN を使う場合: ```html ``` ## 公式プラグイン ### AdvancedFormat - - AdvancedFormat はより多様なフォーマットを表現するために `dayjs().format` API を拡張するプラグインです。 + +- AdvancedFormat はより多様なフォーマットを表現するために `dayjs().format` API を拡張するプラグインです。 ```javascript import AdvancedFormat from 'dayjs/plugin/advancedFormat' @@ -57,17 +58,18 @@ dayjs().format('Q Do k kk X x') 追加されるフォーマットの一覧: -| フォーマット | 出力 | 説明 | -| ------ | ---------------- | ------------------------------------- | -| `Q` | 1-4 | 四半期 | -| `Do` | 1st 2nd ... 31st | 序数付きの日 | -| `k` | 1-23 | 1始まりの時間 | -| `kk` | 01-23 | 1始まりで2桁の時間 | -| `X` | 1360013296 | Unix タイムスタンプ (秒) | -| `x` | 1360013296123 | Unix タイムスタンプ (ミリ秒) | +| フォーマット | 出力 | 説明 | +| ------------ | ---------------- | ---------------------------- | +| `Q` | 1-4 | 四半期 | +| `Do` | 1st 2nd ... 31st | 序数付きの日 | +| `k` | 1-23 | 1 始まりの時間 | +| `kk` | 01-23 | 1 始まりで 2 桁の時間 | +| `X` | 1360013296 | Unix タイムスタンプ (秒) | +| `x` | 1360013296123 | Unix タイムスタンプ (ミリ秒) | ### LocalizedFormat - - LocalizedFormat extends `dayjs().format` API to supply localized format options. + +- LocalizedFormat extends `dayjs().format` API to supply localized format options. ```javascript import LocalizedFormat from 'dayjs/plugin/localizedFormat' @@ -89,7 +91,8 @@ List of added formats: | `LLLL` | dddd, MMMM D, YYYY h:mm A | Thursday, August 16, 2018 8:02 PM | ### RelativeTime - - RelativeTime は日付を文字列で表現された相対的な時刻(例: 3 hours ago)にフォーマットする `.from` `.to` `.fromNow` `.toNow` APIを追加します。 + +- RelativeTime は日付を文字列で表現された相対的な時刻(例: 3 hours ago)にフォーマットする `.from` `.to` `.fromNow` `.toNow` API を追加します。 ```javascript import relativeTime from 'dayjs/plugin/relativeTime' @@ -108,58 +111,60 @@ dayjs().toNow() #### Time from now `.fromNow(withoutSuffix?: boolean)` -* String を返します +- String を返します ある日付から現在を見た時の相対的な時刻を返します。 -#### Time from X `.from(compared: Dayjs, withoutSuffix?: boolean)` +#### Time from X `.from(compared: Dayjs, withoutSuffix?: boolean)` -* String を返します +- String を返します ある日付から引数として渡した日付を見た時の相対的な時刻を返します。 #### Time to now `.toNow(withoutSuffix?: boolean)` -* String を返します +- String を返します 現在からある日付を見た時の相対的な時刻を返します。 -#### Time to X `.to(compared: Dayjs, withoutSuffix?: boolean)` +#### Time to X `.to(compared: Dayjs, withoutSuffix?: boolean)` -* String を返します +- String を返します 引数として渡した日付からある日付を見た時の相対的な時刻を返します。 -| Range | Key | Sample Output | -| ------------------------ | ---- | -------------------------------- | -| 0 to 44 seconds | s | a few seconds ago | -| 45 to 89 seconds | m | a minute ago | -| 90 seconds to 44 minutes | mm | 2 minutes ago ... 44 minutes ago | -| 45 to 89 minutes | h | an hour ago | -| 90 minutes to 21 hours | hh | 2 hours ago ... 21 hours ago | -| 22 to 35 hours | d | a day ago | -| 36 hours to 25 days | dd | 2 days ago ... 25 days ago | -| 26 to 45 days | M | a month ago | -| 46 days to 10 months | MM | 2 months ago ... 10 months ago | -| 11 months to 17months | y | a year ago | -| 18 months+ | yy | 2 years ago ... 20 years ago | +| Range | Key | Sample Output | +| ------------------------ | --- | -------------------------------- | +| 0 to 44 seconds | s | a few seconds ago | +| 45 to 89 seconds | m | a minute ago | +| 90 seconds to 44 minutes | mm | 2 minutes ago ... 44 minutes ago | +| 45 to 89 minutes | h | an hour ago | +| 90 minutes to 21 hours | hh | 2 hours ago ... 21 hours ago | +| 22 to 35 hours | d | a day ago | +| 36 hours to 25 days | dd | 2 days ago ... 25 days ago | +| 26 to 45 days | M | a month ago | +| 46 days to 10 months | MM | 2 months ago ... 10 months ago | +| 11 months to 17months | y | a year ago | +| 18 months+ | yy | 2 years ago ... 20 years ago | ### IsLeapYear - - IsLeapYear はある `Dayjs` オブジェクトがうるう年かどうかを Boolean で返す `.isLeapYear` APIを追加します。 + +- IsLeapYear はある `Dayjs` オブジェクトがうるう年かどうかを Boolean で返す `.isLeapYear` API を追加します。 ```javascript import isLeapYear from 'dayjs/plugin/isLeapYear' dayjs.extend(isLeapYear) -dayjs('2000-01-01').isLeapYear(); // true +dayjs('2000-01-01').isLeapYear() // true ``` ### BuddhistEra + - BuddhistEra は仏滅紀元 (仏暦、B.E.) を表現するフォーマットを提供するために `dayjs().format` API を拡張します。 - 仏滅紀元(ぶつめつきげん、英:Buddhist calendar)とは、釈迦が入滅したとされる年、またはその翌年を元年とする紀年法である。 -仏暦(ぶつれき)ともいう。東南アジアの仏教徒の多い国などで用いられている。([Wikipedia](https://ja.wikipedia.org/wiki/%E4%BB%8F%E6%BB%85%E7%B4%80%E5%85%83)) -- 手動で仏暦を計算するには、ちょうど543を年に足します。例として西暦1977年5月26日は仏暦2520年5月26日と表示されます。(1977 + 543) + 仏暦(ぶつれき)ともいう。東南アジアの仏教徒の多い国などで用いられている。([Wikipedia](https://ja.wikipedia.org/wiki/%E4%BB%8F%E6%BB%85%E7%B4%80%E5%85%83)) +- 手動で仏暦を計算するには、ちょうど 543 を年に足します。例として西暦 1977 年 5 月 26 日は仏暦 2520 年 5 月 26 日と表示されます。(1977 + 543) ```javascript import buddhistEra from 'dayjs/plugin/buddhistEra' @@ -171,60 +176,65 @@ dayjs().format('BBBB BB') 追加されるフォーマットの一覧: -| フォーマット | 出力 | 説明 | -| --------- | ---- | ------------------ | -| `BBBB` | 2561 | 完全な仏暦 (年 + 543) | -| `BB` | 61 | 2桁の仏暦 | +| フォーマット | 出力 | 説明 | +| ------------ | ---- | --------------------- | +| `BBBB` | 2561 | 完全な仏暦 (年 + 543) | +| `BB` | 61 | 2 桁の仏暦 | ### IsSameOrAfter - - IsSameOrAfter はある日付が別の日付と同じまたはそれ以降であるかどうかを `Boolean` で返す `.isSameOrAfter()` APIを追加します。 + +- IsSameOrAfter はある日付が別の日付と同じまたはそれ以降であるかどうかを `Boolean` で返す `.isSameOrAfter()` API を追加します。 ```javascript import isSameOrAfter from 'dayjs/plugin/isSameOrAfter' dayjs.extend(isSameOrAfter) -dayjs('2010-10-20').isSameOrAfter('2010-10-19', 'year'); +dayjs('2010-10-20').isSameOrAfter('2010-10-19', 'year') ``` ### IsSameOrBefore - - IsSameOrBefore はある日付が別の日付と同じまたはそれ以前であるかどうかを `boolean` で返す `.isSameOrBefore()` APIを追加します。 + +- IsSameOrBefore はある日付が別の日付と同じまたはそれ以前であるかどうかを `boolean` で返す `.isSameOrBefore()` API を追加します。 ```javascript import isSameOrBefore from 'dayjs/plugin/isSameOrBefore' dayjs.extend(isSameOrBefore) -dayjs('2010-10-20').isSameOrBefore('2010-10-19', 'year'); +dayjs('2010-10-20').isSameOrBefore('2010-10-19', 'year') ``` ### IsBetween - - IsBetween はある日付が別の2つの日付の間にあるかどうかを `Boolean` で返す `.isBetween()` APIを追加します。 + +- IsBetween はある日付が別の 2 つの日付の間にあるかどうかを `Boolean` で返す `.isBetween()` API を追加します。 ```javascript import isBetween from 'dayjs/plugin/isBetween' dayjs.extend(isBetween) -dayjs('2010-10-20').isBetween('2010-10-19', dayjs('2010-10-25'), 'year'); -dayjs('2016-10-30').isBetween('2016-01-01', '2016-10-30', null, '[)'); +dayjs('2010-10-20').isBetween('2010-10-19', dayjs('2010-10-25'), 'year') +dayjs('2016-10-30').isBetween('2016-01-01', '2016-10-30', null, '[)') // '[' indicates inclusion, '(' indicates exclusion ``` + ### DayOfYear - DayOfYear adds `.dayOfYear()` API to returns a `number` indicating the `Dayjs`'s day of the year, or to set the day of the year. ```javascript -import dayOfYear from "dayjs/plugin/dayOfYear"; +import dayOfYear from 'dayjs/plugin/dayOfYear' -dayjs.extend(dayOfYear); +dayjs.extend(dayOfYear) -dayjs("2010-01-01").dayOfYear(); // 1 -dayjs("2010-01-01").dayOfYear(365); // 2010-12-31 +dayjs('2010-01-01').dayOfYear() // 1 +dayjs('2010-01-01').dayOfYear(365) // 2010-12-31 ``` ### WeekOfYear - - WeekOfYear はある `Dayjs` オブジェクトがその年の何週目であるかを `Number` で返す `.week()` APIを追加します。 + +- WeekOfYear はある `Dayjs` オブジェクトがその年の何週目であるかを `Number` で返す `.week()` API を追加します。 ```javascript import weekOfYear from 'dayjs/plugin/weekOfYear' @@ -235,6 +245,7 @@ dayjs('06/27/2018').week() // 26 ``` ### QuarterOfYear + - QuarterOfYear add `.quarter()` API to return to which quarter of the year belongs a date ```javascript @@ -242,11 +253,12 @@ import quarterOfYear from 'dayjs/plugin/quarterOfYear' dayjs.extend(quarterOfYear) -dayjs('2010-04-01').quarter(); // 2 +dayjs('2010-04-01').quarter() // 2 ``` ### CustomParseFormat - - CustomParseFormat extends `dayjs()` constructor to support custom formats of input strings. + +- CustomParseFormat extends `dayjs()` constructor to support custom formats of input strings. To escape characters, wrap them in square brackets (e.g. `[G]`). Punctuation symbols (-:/.()) do not need to be wrapped. @@ -261,29 +273,29 @@ dayjs('05/02/69 1:02:03 PM -05:00', 'MM/DD/YY H:mm:ss A Z') #### List of all available format tokens -| Format | Output | Description | -| ------ | ---------------- | --------------------------------- | -| `YY` | 18 | Two-digit year | -| `YYYY` | 2018 | Four-digit year | -| `M` | 1-12 | Month, beginning at 1 | -| `MM` | 01-12 | Month, 2-digits | -| `D` | 1-31 | Day of month | -| `DD` | 01-31 | Day of month, 2-digits | -| `H` | 0-23 | Hours | -| `HH` | 00-23 | Hours, 2-digits | -| `h` | 1-12 | Hours, 12-hour clock | -| `hh` | 01-12 | Hours, 12-hour clock, 2-digits | -| `m` | 0-59 | Minutes | -| `mm` | 00-59 | Minutes, 2-digits | -| `s` | 0-59 | Seconds | -| `ss` | 00-59 | Seconds, 2-digits | -| `S` | 0-9 | Hundreds of milliseconds, 1-digit | -| `SS` | 00-99 | Tens of milliseconds, 2-digits | -| `SSS` | 000-999 | Milliseconds, 3-digits | -| `Z` | -5:00 | Offset from UTC | -| `ZZ` | -0500 | Compact offset from UTC, 2-digits | -| `A` | AM PM | Post or ante meridiem, upper-case | -| `a` | am pm | Post or ante meridiem, lower-case | +| Format | Output | Description | +| ------ | ------- | --------------------------------- | +| `YY` | 18 | Two-digit year | +| `YYYY` | 2018 | Four-digit year | +| `M` | 1-12 | Month, beginning at 1 | +| `MM` | 01-12 | Month, 2-digits | +| `D` | 1-31 | Day of month | +| `DD` | 01-31 | Day of month, 2-digits | +| `H` | 0-23 | Hours | +| `HH` | 00-23 | Hours, 2-digits | +| `h` | 1-12 | Hours, 12-hour clock | +| `hh` | 01-12 | Hours, 12-hour clock, 2-digits | +| `m` | 0-59 | Minutes | +| `mm` | 00-59 | Minutes, 2-digits | +| `s` | 0-59 | Seconds | +| `ss` | 00-59 | Seconds, 2-digits | +| `S` | 0-9 | Hundreds of milliseconds, 1-digit | +| `SS` | 00-99 | Tens of milliseconds, 2-digits | +| `SSS` | 000-999 | Milliseconds, 3-digits | +| `Z` | -5:00 | Offset from UTC | +| `ZZ` | -0500 | Compact offset from UTC, 2-digits | +| `A` | AM PM | Post or ante meridiem, upper-case | +| `a` | am pm | Post or ante meridiem, lower-case | ## カスタマイズ @@ -297,16 +309,16 @@ dayjs('05/02/69 1:02:03 PM -05:00', 'MM/DD/YY H:mm:ss A Z') export default (option, dayjsClass, dayjsFactory) => { // dayjs() を拡張する // 例) dayjs().isSameOrBefore() を追加 - dayjsClass.prototype.isSameOrBefore = function (arguments) {} + dayjsClass.prototype.isSameOrBefore = function(arguments) {} // dayjs() を拡張する // 例) dayjs().utc() を追加 - dayjsFactory.utc = (arguments) => {} + dayjsFactory.utc = arguments => {} // 既存 API の上書き // 例) dayjs().format() を拡張 const oldFormat = dayjsClass.prototype.format - dayjsClass.prototype.format = function (arguments) { + dayjsClass.prototype.format = function(arguments) { // 既存のフォーマット const result = oldFormat(arguments) // 変更後のフォーマット diff --git a/docs/ja/README-ja.md b/docs/ja/README-ja.md index aaf1fb89..6866bd2e 100644 --- a/docs/ja/README-ja.md +++ b/docs/ja/README-ja.md @@ -23,17 +23,20 @@ > Day.js は日付と時刻をパース・検証・操作・表示する最小のモダンブラウザ向け JavaScript ライブラリであり、 Moment.js の API との広い互換性を持ちます。 Moment.js を使ったことがあればすぐにでも Day.js を使い始めることができます。 - ```js -dayjs().startOf('month').add(1, 'day').set('year', 2018).format('YYYY-MM-DD HH:mm:ss'); +dayjs() + .startOf('month') + .add(1, 'day') + .set('year', 2018) + .format('YYYY-MM-DD HH:mm:ss') ``` -* 🕒 Moment.js と類似した API と使用法 -* 💪 イミュータブル -* 🔥 メソッドチェーン -* 🌐 国際化サポート (I18n) -* 📦 2kb の軽量ライブラリ -* 👫 全ブラウザをサポート +- 🕒 Moment.js と類似した API と使用法 +- 💪 イミュータブル +- 🔥 メソッドチェーン +- 🌐 国際化サポート (I18n) +- 📦 2kb の軽量ライブラリ +- 👫 全ブラウザをサポート --- @@ -56,7 +59,9 @@ dayjs('2018-08-08') // パース dayjs().format('{YYYY} MM-DDTHH:mm:ss SSS [Z] A') // 表示 -dayjs().set('month', 3).month() // get & set +dayjs() + .set('month', 3) + .month() // get & set dayjs().add(1, 'year') // 操作 @@ -76,7 +81,9 @@ import 'dayjs/locale/es' // 必要に応じて読み込み dayjs.locale('es') // スペイン語をグローバルロケールとして適用 -dayjs('2018-05-05').locale('zh-cn').format() // 簡体字中国語を特定のインスタンスにのみ適用 +dayjs('2018-05-05') + .locale('zh-cn') + .format() // 簡体字中国語を特定のインスタンスにのみ適用 ``` 📚[国際化](./I18n.md) @@ -97,4 +104,4 @@ dayjs().format('Q Do k kk X x') // 多様なフォーマットが利用可能に ## ライセンス -Day.js は [MIT License](../../LICENSE) のもとで利用を許諾します。 +Day.js は [MIT License](../../LICENSE) のもとで利用を許諾します。 diff --git a/docs/ko/API-reference.md b/docs/ko/API-reference.md index ec384015..073c1535 100644 --- a/docs/ko/API-reference.md +++ b/docs/ko/API-reference.md @@ -31,7 +31,7 @@ Day.js는 네이티브 `Date.prototype`을 수정하는 대신 `Dayjs` 오브젝 - [End of Time `.endOf(unit: string)`](#end-of-time-endofunit--string) - [Displaying](#displaying) - [Format `.format(stringWithTokens: string)`](#format-formatstringwithtokens--string) - - [List of all available formats](#list-of-all-available-formats) + - [List of all available formats](#list-of-all-available-formats) - [Difference `.diff(compared: Dayjs, unit: string (default: 'milliseconds'), float?: boolean)`](#difference-diffcompared--dayjs--unit--string-default--milliseconds--float--boolean) - [Unix Timestamp (milliseconds) `.valueOf()`](#unix-timestamp-milliseconds-valueof) - [Unix Timestamp (seconds) `.unix()`](#unix-timestamp-seconds-unix) @@ -64,7 +64,7 @@ Day.js는 네이티브 `Date.prototype`을 수정하는 대신 `Dayjs` 오브젝 매개 변수없이 호출하면 현재 날짜와 시간을 가진 새로운 `Dayjs` 오브젝트가 반환됩니다. ```js -dayjs(); +dayjs() ``` Day.js는 다른 날짜 형식도 구분 분석합니다. @@ -72,13 +72,13 @@ Day.js는 다른 날짜 형식도 구분 분석합니다. #### [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) string ```js -dayjs('2018-04-04T16:00:00.000Z'); +dayjs('2018-04-04T16:00:00.000Z') ``` #### Native Javascript Date object ```js -dayjs(new Date(2018, 8, 18)); +dayjs(new Date(2018, 8, 18)) ``` #### Unix Timestamp (milliseconds) @@ -86,7 +86,7 @@ dayjs(new Date(2018, 8, 18)); Returns a `Dayjs` from a Unix timestamp (milliseconds since the Unix Epoch) ```js -dayjs(1318781876406); +dayjs(1318781876406) ``` ### Unix Timestamp (seconds) `.unix(value: number)` @@ -94,20 +94,21 @@ dayjs(1318781876406); Returns a `Dayjs` from a Unix timestamp (seconds since the Unix Epoch) ```js -dayjs.unix(1318781876); -dayjs.unix(1318781876.721); +dayjs.unix(1318781876) +dayjs.unix(1318781876.721) ``` ### Custom Parse Format -* parse custom formats `dayjs("12-25-1995", "MM-DD-YYYY")` in plugin [`CustomParseFormat`](./Plugin.md#customparseformat) + +- parse custom formats `dayjs("12-25-1995", "MM-DD-YYYY")` in plugin [`CustomParseFormat`](./Plugin.md#customparseformat) ### Clone `.clone() | dayjs(original: Dayjs)` `Dayjs` 클론 오브젝트를 반환합니다. ```js -dayjs().clone(); -dayjs(dayjs('2019-01-25')); // passing a Dayjs object to a constructor will also clone it +dayjs().clone() +dayjs(dayjs('2019-01-25')) // passing a Dayjs object to a constructor will also clone it ``` ### Validation `.isValid()` @@ -115,7 +116,7 @@ dayjs(dayjs('2019-01-25')); // passing a Dayjs object to a constructor will also `Dayjs` 날짜가 유효한지 확인합니다. 반환 타입은 `boolean` 입니다. ```js -dayjs().isValid(); +dayjs().isValid() ``` ## Get and Set @@ -125,7 +126,7 @@ dayjs().isValid(); `Dayjs`에서 연도 가져옵니다. 반환 타입은 `number` 입니다. ```js -dayjs().year(); +dayjs().year() ``` ### Month `.month()` @@ -133,7 +134,7 @@ dayjs().year(); `Dayjs`에서 달을 가져옵니다. 반환 타입은 `number` 입니다. ```js -dayjs().month(); +dayjs().month() ``` ### Day of the Month `.date()` @@ -141,7 +142,7 @@ dayjs().month(); `Dayjs`에서 날짜를 가져옵니다. 반환 타입은 `number` 입니다. ```js -dayjs().date(); +dayjs().date() ``` ### Day of the Week `.day()` @@ -149,7 +150,7 @@ dayjs().date(); `Dayjs`에서 요일을 가져옵니다. 반환 타입은 `number` 입니다. ```js -dayjs().day(); +dayjs().day() ``` ### Hour `.hour()` @@ -157,7 +158,7 @@ dayjs().day(); `Dayjs`에서 시를 가져옵니다. 반환 타입은 `number` 입니다. ```js -dayjs().hour(); +dayjs().hour() ``` ### Minute `.minute()` @@ -165,7 +166,7 @@ dayjs().hour(); `Dayjs`에서 분을 가져옵니다. 반환 타입은 `number` 입니다. ```js -dayjs().minute(); +dayjs().minute() ``` ### Second `.second()` @@ -173,7 +174,7 @@ dayjs().minute(); `Dayjs`에서 초를 가져옵니다. 반환 타입은 `number` 입니다. ```js -dayjs().second(); +dayjs().second() ``` ### Millisecond `.millisecond()` @@ -181,7 +182,7 @@ dayjs().second(); `Dayjs`에서 밀리 초를 가져옵니다. 반환 타입은 `number` 입니다. ```js -dayjs().millisecond(); +dayjs().millisecond() ``` ### Set `.set(unit: string, value: number)` @@ -189,9 +190,9 @@ dayjs().millisecond(); 변경 사항이 적용된 `Dayjs`를 반환합니다. ```js -dayjs().set('date', 1); -dayjs().set('month', 3); // April -dayjs().set('second', 30); +dayjs().set('date', 1) +dayjs().set('month', 3) // April +dayjs().set('second', 30) ``` #### List of all available units @@ -214,7 +215,8 @@ dayjs().set('second', 30); ```js dayjs('2019-01-25') .add(1, 'day') - .subtract(1, 'year').toString(); // Fri, 26 Jan 2018 00:00:00 GMT + .subtract(1, 'year') + .toString() // Fri, 26 Jan 2018 00:00:00 GMT ``` ### Add `.add(value: number, unit: string)` @@ -222,7 +224,7 @@ dayjs('2019-01-25') 지정한 시간을 더한 `Dayjs` 오브젝트 복제본을 반환합니다. ```js -dayjs().add(7, 'day'); +dayjs().add(7, 'day') ``` ### Subtract `.subtract(value: number, unit: string)` @@ -230,7 +232,7 @@ dayjs().add(7, 'day'); 지정한 시간을 뺀 `Dayjs` 오브젝트 복제본을 반환합니다. ```js -dayjs().subtract(7, 'year'); +dayjs().subtract(7, 'year') ``` ### Start of Time `.startOf(unit: string)` @@ -238,7 +240,7 @@ dayjs().subtract(7, 'year'); 특정 시간 단위의 시작 시점에 대한 시간을 `Dayjs` 오브젝트 복제본으로 반환합니다. ```js -dayjs().startOf('week'); // Depends on `weekStart` in locale +dayjs().startOf('week') // Depends on `weekStart` in locale ``` ### End of Time `.endOf(unit: string)` @@ -246,7 +248,7 @@ dayjs().startOf('week'); // Depends on `weekStart` in locale 특정 시간 단위의 끝나는 시점에 대한 시간을 `Dayjs` 오브젝트 복제본으로 반환힙니다. ```js -dayjs().endOf('month'); +dayjs().endOf('month') ``` ## Displaying @@ -257,40 +259,40 @@ dayjs().endOf('month'); 예외하고 싶은 문자일 경우, 대괄호나 중괄호를 사용하여 묶으면됩니다. (예, `[G] {um}`) ```js -dayjs().format(); // 분과 초가 없는 ISO5801 형식의 현재 시간을 나타냅니다. 예: '2020-04-02T08:02:17-05:00' +dayjs().format() // 분과 초가 없는 ISO5801 형식의 현재 시간을 나타냅니다. 예: '2020-04-02T08:02:17-05:00' -dayjs('2019-01-25').format('{YYYY} MM-DDTHH:mm:ssZ[Z]'); // '{2019} 01-25T00:00:00-02:00Z' +dayjs('2019-01-25').format('{YYYY} MM-DDTHH:mm:ssZ[Z]') // '{2019} 01-25T00:00:00-02:00Z' -dayjs('2019-01-25').format('DD/MM/YYYY'); // '25/01/2019' +dayjs('2019-01-25').format('DD/MM/YYYY') // '25/01/2019' ``` #### List of all available formats | Format | Output | Description | | ------ | ---------------- | ------------------------------------- | -| `YY` | 18 | 두 자리로 된 연도 | -| `YYYY` | 2018 | 네 자리로 된 연도 | -| `M` | 1-12 | 달, 1부터 시작 | -| `MM` | 01-12 | 달, 두 자리로 표현 | -| `MMM` | Jan-Dec | 월 이름 약어 | +| `YY` | 18 | 두 자리로 된 연도 | +| `YYYY` | 2018 | 네 자리로 된 연도 | +| `M` | 1-12 | 달, 1부터 시작 | +| `MM` | 01-12 | 달, 두 자리로 표현 | +| `MMM` | Jan-Dec | 월 이름 약어 | | `MMMM` | January-December | 월 이름 | | `D` | 1-31 | 일 | -| `DD` | 01-31 | 일, 두 자리로 표현 | -| `d` | 0-6 | 요일, 일요일은 0 | +| `DD` | 01-31 | 일, 두 자리로 표현 | +| `d` | 0-6 | 요일, 일요일은 0 | | `dd` | Su-Sa | The min name of the day of the week | | `ddd` | Sun-Sat | The short name of the day of the week | -| `dddd` | Sunday-Saturday | 요일 이름 | +| `dddd` | Sunday-Saturday | 요일 이름 | | `H` | 0-23 | 시간 | -| `HH` | 00-23 | 시간, 두 자리로 표현 | +| `HH` | 00-23 | 시간, 두 자리로 표현 | | `h` | 1-12 | 시간, 12시간 | -| `hh` | 01-12 | 시간, 12시간, 두 자리로 표현 | +| `hh` | 01-12 | 시간, 12시간, 두 자리로 표현 | | `m` | 0-59 | 분 | -| `mm` | 00-59 | 분, 두 자리로 표현 | +| `mm` | 00-59 | 분, 두 자리로 표현 | | `s` | 0-59 | 초 | -| `ss` | 00-59 | 초, 두 자리로 표현 | -| `SSS` | 000-999 | 밀리 초, 3자리로 표현 | -| `Z` | +5:00 | UTC로부터 추가된 시간 | -| `ZZ` | +0500 | UTC로부터 추가된 시간, 두자리로 표현 | +| `ss` | 00-59 | 초, 두 자리로 표현 | +| `SSS` | 000-999 | 밀리 초, 3자리로 표현 | +| `Z` | +5:00 | UTC로부터 추가된 시간 | +| `ZZ` | +0500 | UTC로부터 추가된 시간, 두자리로 표현 | | `A` | AM PM | | | `a` | am pm | | @@ -302,12 +304,12 @@ dayjs('2019-01-25').format('DD/MM/YYYY'); // '25/01/2019' 두 `Dayjs` 오브젝트 차이를 지정한 단위로 가져옵니다. 반환 타입은 `number` 입니다. ```js -const date1 = dayjs('2019-01-25'); -const date2 = dayjs('2018-06-05'); -date1.diff(date2); // 20214000000 -date1.diff(date2, 'month'); // 7 -date1.diff(date2, 'month', true); // 7.645161290322581 -date1.diff(date2, 'day'); // 233 +const date1 = dayjs('2019-01-25') +const date2 = dayjs('2018-06-05') +date1.diff(date2) // 20214000000 +date1.diff(date2, 'month') // 7 +date1.diff(date2, 'month', true) // 7.645161290322581 +date1.diff(date2, 'day') // 233 ``` ### Unix Timestamp (milliseconds) `.valueOf()` @@ -315,7 +317,7 @@ date1.diff(date2, 'day'); // 233 `Dayjs`에 대한 Unix Epoch 이후의 밀리 초 시간을 가져옵니다. 반환 타입은 `number` 입니다. ```js -dayjs('2019-01-25').valueOf(); // 1548381600000 +dayjs('2019-01-25').valueOf() // 1548381600000 ``` ### Unix Timestamp (seconds) `.unix()` @@ -323,7 +325,7 @@ dayjs('2019-01-25').valueOf(); // 1548381600000 `Dayjs`에 대한 Unix Epoch 이후의 초 시간을 가져옵니다. 반환 타입은 `number` 입니다. ```js -dayjs('2019-01-25').unix(); // 1548381600 +dayjs('2019-01-25').unix() // 1548381600 ``` ### UTC Offset (minutes) `.utcOffset()` @@ -331,7 +333,7 @@ dayjs('2019-01-25').unix(); // 1548381600 Returns the UTC offset in minutes for the `Dayjs`. ```js -dayjs().utcOffset(); +dayjs().utcOffset() ``` ### Days in the Month `.daysInMonth()` @@ -339,15 +341,15 @@ dayjs().utcOffset(); `Dayjs`에서 표기하는 달에서 일수를 가져옵니다. 반환 타입은 `number` 입니다. ```js -dayjs('2019-01-25').daysInMonth(); // 31 +dayjs('2019-01-25').daysInMonth() // 31 ``` ### As Javascript Date `.toDate()` -`Dayjs` 오브젝트에서 파싱된 네이티브 `Date` 오브젝트 복사본을 반환합니다. +`Dayjs` 오브젝트에서 파싱된 네이티브 `Date` 오브젝트 복사본을 반환합니다. ```js -dayjs('2019-01-25').toDate(); +dayjs('2019-01-25').toDate() ``` ### As Array `.toArray()` @@ -355,7 +357,7 @@ dayjs('2019-01-25').toDate(); 새로운 `Date()`로부터 매개변수로 입력한 날짜를 가져옵니다. 반환 타입은 `array` 입니다. ```js -dayjs('2019-01-25').toArray(); // [ 2019, 01, 25, 0, 0, 0, 0 ] +dayjs('2019-01-25').toArray() // [ 2019, 01, 25, 0, 0, 0, 0 ] ``` ### As JSON `.toJSON()` @@ -363,7 +365,7 @@ dayjs('2019-01-25').toArray(); // [ 2019, 01, 25, 0, 0, 0, 0 ] ISO8601에 대한 형식으로 `Dayjs`를 출력합니다. 반환 타입은 `string` 입니다. ```js -dayjs('2019-01-25').toJSON(); // '2019-01-25T02:00:00.000Z' +dayjs('2019-01-25').toJSON() // '2019-01-25T02:00:00.000Z' ``` ### As ISO 8601 String `.toISOString()` @@ -371,7 +373,7 @@ dayjs('2019-01-25').toJSON(); // '2019-01-25T02:00:00.000Z' ISO8601에 대한 형식으로 `Dayjs`를 출력합니다. 반환 타입은 `string` 입니다. ```js -dayjs('2019-01-25').toISOString(); // '2019-01-25T02:00:00.000Z' +dayjs('2019-01-25').toISOString() // '2019-01-25T02:00:00.000Z' ``` ### As Object `.toObject()` @@ -379,7 +381,7 @@ dayjs('2019-01-25').toISOString(); // '2019-01-25T02:00:00.000Z' 날짜 속성을 가진 `object` 타입 값으로 반환합니다. ```js -dayjs('2019-01-25').toObject(); +dayjs('2019-01-25').toObject() /* { years: 2019, months: 0, date: 25, @@ -394,7 +396,7 @@ dayjs('2019-01-25').toObject(); 날짜를 `string` 타입 값으로 반환합니다. ```js -dayjs('2019-01-25').toString(); // 'Fri, 25 Jan 2019 02:00:00 GMT' +dayjs('2019-01-25').toString() // 'Fri, 25 Jan 2019 02:00:00 GMT' ``` ## Query @@ -404,8 +406,8 @@ dayjs('2019-01-25').toString(); // 'Fri, 25 Jan 2019 02:00:00 GMT' `Dayjs`가 다른 `Dayjs`보다 앞선 시점인지를 확인합니다. 반환 타입은 `boolean` 입니다. ```js -dayjs().isBefore(dayjs()); // false -dayjs().isBefore(dayjs(), 'year'); // false +dayjs().isBefore(dayjs()) // false +dayjs().isBefore(dayjs(), 'year') // false ``` ### Is Same `.isSame(compared: Dayjs, unit?: string)` @@ -413,8 +415,8 @@ dayjs().isBefore(dayjs(), 'year'); // false `Dayjs`가 다른 `Dayjs`과 동일한 시점인지를 확인합니다. 반환 타입은 `boolean` 입니다. ```js -dayjs().isSame(dayjs()); // true -dayjs().isSame(dayjs(), 'year'); // true +dayjs().isSame(dayjs()) // true +dayjs().isSame(dayjs(), 'year') // true ``` ### Is After `.isAfter(compared: Dayjs, unit?: string)` @@ -422,8 +424,8 @@ dayjs().isSame(dayjs(), 'year'); // true `Dayjs`가 다른 `Dayjs`보다 뒷선 시점인지를 확인합니다. 반환 타입은 `boolean` 입니다. ```js -dayjs().isAfter(dayjs()); // false -dayjs().isAfter(dayjs(), 'year'); // false +dayjs().isAfter(dayjs()) // false +dayjs().isAfter(dayjs(), 'year') // false ``` ### Is a Dayjs `.isDayjs(compared: any)` @@ -431,8 +433,8 @@ dayjs().isAfter(dayjs(), 'year'); // false Returns a `boolean` indicating whether a variable is a dayjs object or not. ```js -dayjs.isDayjs(dayjs()); // true -dayjs.isDayjs(new Date()); // false +dayjs.isDayjs(dayjs()) // true +dayjs.isDayjs(new Date()) // false ``` The operator `instanceof` works equally well: @@ -484,4 +486,3 @@ plugin [`IsBetween`](./Plugin.md#isbetween) `.quarter` to get quarter of the year plugin [`QuarterOfYear`](./Plugin.md#quarterofyear) - diff --git a/docs/ko/I18n.md b/docs/ko/I18n.md index a45656d6..9862f0d3 100644 --- a/docs/ko/I18n.md +++ b/docs/ko/I18n.md @@ -16,7 +16,7 @@ Day.js에서 기본 locale 값은 영어(미국) 입니다. #### Changing locale globally -* locale 문자열로 반환합니다. +- locale 문자열로 반환합니다. ```js import 'dayjs/locale/es' @@ -28,23 +28,25 @@ dayjs.locale(customizedLocaleObject) // 커스텀 locale 사용 dayjs.locale('en') // switch back to default English locale globally ``` -* 글로벌 locale을 변경해도 기존 인스턴스에는 영향을 주지 않습니다. +- 글로벌 locale을 변경해도 기존 인스턴스에는 영향을 주지 않습니다. #### Changing locales locally -* 새로운 locale로 전환하여 새로운 'Dayjs' 오브젝트를 반환합니다. +- 새로운 locale로 전환하여 새로운 'Dayjs' 오브젝트를 반환합니다. 정확히 `dayjs#locale`과 동일하지만, 특정 인스턴스에서만 locale을 사용합니다. ```js import 'dayjs/locale/es' -dayjs().locale('es').format() // 국지적으로 locale을 로드하여 사용합니다.. +dayjs() + .locale('es') + .format() // 국지적으로 locale을 로드하여 사용합니다.. dayjs('2018-4-28', { locale: 'es' }) // through constructor ``` ## Installation -* NPM: +- NPM: ```javascript import 'dayjs/locale/es' // load on demand @@ -52,17 +54,22 @@ import 'dayjs/locale/es' // load on demand // import locale_es from 'dayjs/locale/es' -> load and get locale_es locale object dayjs.locale('es') // 글로벌 하게 사용 -dayjs().locale('es').format() // 특정 인스턴스에서 사용. +dayjs() + .locale('es') + .format() // 특정 인스턴스에서 사용. ``` -* CDN: +- CDN: + ```html @@ -75,6 +82,7 @@ dayjs().locale('es').format() // 특정 인스턴스에서 사용. locale을 공휴하기위해 풀 리퀘스트를 여십시오. Day.js locale 오브젝트 템플릿 입니다. + ```javascript const localeObject = { name: 'es', // name String @@ -104,6 +112,7 @@ const localeObject = { ``` Day.js locale 파일 템플릿 입니다. + ```javascript import dayjs from 'dayjs' diff --git a/docs/ko/Installation.md b/docs/ko/Installation.md index b1863041..2e0825f2 100644 --- a/docs/ko/Installation.md +++ b/docs/ko/Installation.md @@ -2,7 +2,7 @@ Day.js를 가져오는 방법은 여러가지가 있습니다: -* NPM: +- NPM: ```console npm install dayjs --save @@ -12,19 +12,19 @@ npm install dayjs --save import dayjs from 'dayjs' // Or CommonJS // var dayjs = require('dayjs'); -dayjs().format(); +dayjs().format() ``` -* CDN: +- CDN: ```html ``` -* 다운 받아 셀프 호스팅: +- 다운 받아 셀프 호스팅: [https://unpkg.com/dayjs/](https://unpkg.com/dayjs/)에서 Day.js 의 최신버전을 받을 수 있습니다. diff --git a/docs/ko/Plugin.md b/docs/ko/Plugin.md index 38e31068..cd96ff2d 100644 --- a/docs/ko/Plugin.md +++ b/docs/ko/Plugin.md @@ -10,7 +10,7 @@ #### Extend -* dayjs를 반환합니다. +- dayjs를 반환합니다. 플러그인을 사용합니다. @@ -22,7 +22,7 @@ dayjs.extend(plugin, options) // with plugin options ## Installation -* NPM: +- NPM: ```javascript import dayjs from 'dayjs' @@ -31,20 +31,22 @@ import AdvancedFormat from 'dayjs/plugin/advancedFormat' // load on demand dayjs.extend(AdvancedFormat) // use plugin ``` -* CDN: +- CDN: + ```html ``` ## List of official plugins ### AdvancedFormat - - AdvancedFormat은 더 많은 형식 옵션을 제공하기위해 `dayjs().format` API를 확장합니다. + +- AdvancedFormat은 더 많은 형식 옵션을 제공하기위해 `dayjs().format` API를 확장합니다. ```javascript import advancedFormat from 'dayjs/plugin/advancedFormat' @@ -56,17 +58,18 @@ dayjs().format('Q Do k kk X x') 추가된 형식 목록: -| Format | Output | Description | -| ------ | ---------------- | ------------------------------------- | -| `Q` | 1-4 | 분기 | -| `Do` | 1st 2nd ... 31st | 서수형식의 일자 명 | -| `k` | 1-23 | 시간, 1부터 시작 | -| `kk` | 01-23 | 시간, 2자리 표현, 1부터 시작 | -| `X` | 1360013296 | 유닉스 타임스템프, 초 | -| `x` | 1360013296123 | 유닉스 타임스탬프, 밀리 초 | +| Format | Output | Description | +| ------ | ---------------- | ---------------------------- | +| `Q` | 1-4 | 분기 | +| `Do` | 1st 2nd ... 31st | 서수형식의 일자 명 | +| `k` | 1-23 | 시간, 1부터 시작 | +| `kk` | 01-23 | 시간, 2자리 표현, 1부터 시작 | +| `X` | 1360013296 | 유닉스 타임스템프, 초 | +| `x` | 1360013296123 | 유닉스 타임스탬프, 밀리 초 | ### LocalizedFormat - - LocalizedFormat extends `dayjs().format` API to supply localized format options. + +- LocalizedFormat extends `dayjs().format` API to supply localized format options. ```javascript import LocalizedFormat from 'dayjs/plugin/localizedFormat' @@ -88,7 +91,8 @@ List of added formats: | `LLLL` | dddd, MMMM D, YYYY h:mm A | Thursday, August 16, 2018 8:02 PM | ### RelativeTime - - RelativeTime은 `.from`, `.to`, `.fromNow`, `.toNow` API를 추가하여 날짜를 상대 시간 문자열(예: 3 시간전) 으로 표시합니다. + +- RelativeTime은 `.from`, `.to`, `.fromNow`, `.toNow` API를 추가하여 날짜를 상대 시간 문자열(예: 3 시간전) 으로 표시합니다. ```javascript import relativeTime from 'dayjs/plugin/relativeTime' @@ -109,7 +113,7 @@ dayjs().toNow() 지금 시간부터 상대시간을 `string`으로 반환합니다. -#### Time from X `.from(compared: Dayjs, withoutSuffix?: boolean)` +#### Time from X `.from(compared: Dayjs, withoutSuffix?: boolean)` X 시간으로부터 상대시간을 `string`으로 반환합니다.. @@ -117,36 +121,38 @@ X 시간으로부터 상대시간을 `string`으로 반환합니다.. 지금 시간부터 상대시간을 `string`으로 반환합니다. -#### Time to X `.to(compared: Dayjs, withoutSuffix?: boolean)` +#### Time to X `.to(compared: Dayjs, withoutSuffix?: boolean)` X 시간부터 상대시간을 `string`으로 반환합니다. -| 범위 | Key | 간단 출력 | -| ----------------- | ---- | --------------------- | -| 0 초 ~ 44 초 | s | 몇 초 전 | -| 45 초 ~ 89 초 | m | 1 분 전 | -| 90 초 ~ 44 분 | mm | 2 분 전 ~ 44 분 전 | -| 45 분 ~ 89 분 | h | 한 시간 전 | -| 90 분 ~ 21 시간 | hh | 2 시간 전 ~ 21 시간 전 | -| 22 시간 ~ 35 시간 | d | 하루 전 | -| 36 시간 ~ 25 일 | dd | 이틀 전 ~ 25 일 전 | -| 26 일 ~ 45 일 | M | 한달 전 | -| 46 일 ~ 10 달 | MM | 두달 전 ~ 10 달 전 | -| 11 달 ~ 17 달 | y | 일년 전 | -| 18 달 이상 | yy | 2 년 전 ~ 20 년 전 | +| 범위 | Key | 간단 출력 | +| ----------------- | --- | ---------------------- | +| 0 초 ~ 44 초 | s | 몇 초 전 | +| 45 초 ~ 89 초 | m | 1 분 전 | +| 90 초 ~ 44 분 | mm | 2 분 전 ~ 44 분 전 | +| 45 분 ~ 89 분 | h | 한 시간 전 | +| 90 분 ~ 21 시간 | hh | 2 시간 전 ~ 21 시간 전 | +| 22 시간 ~ 35 시간 | d | 하루 전 | +| 36 시간 ~ 25 일 | dd | 이틀 전 ~ 25 일 전 | +| 26 일 ~ 45 일 | M | 한달 전 | +| 46 일 ~ 10 달 | MM | 두달 전 ~ 10 달 전 | +| 11 달 ~ 17 달 | y | 일년 전 | +| 18 달 이상 | yy | 2 년 전 ~ 20 년 전 | ### IsLeapYear - - IsLeapYear은 `.isLeapYear` API를 추가하여 `Dayjs`의 년이 윤년인 경우 `boolean`으로 값을 반환합니다. + +- IsLeapYear은 `.isLeapYear` API를 추가하여 `Dayjs`의 년이 윤년인 경우 `boolean`으로 값을 반환합니다. ```javascript import isLeapYear from 'dayjs/plugin/isLeapYear' dayjs.extend(isLeapYear) -dayjs('2000-01-01').isLeapYear(); // true +dayjs('2000-01-01').isLeapYear() // true ``` ### BuddhistEra + - BuddhistEra는 Buddhist Era (B.E.) 형식 옵션을 제공하기 위해 `dayjs().format` API를 확장합니다. - Buddhist Era 는 캄보디아, 라오스, 미얀마, 태국 그리고 스리랑카, 말레이시아 및 싱가포르의 중국인들에게 종교적 또는 공식적인 행사로 주로 사용하는 1년 단위 번호 체계입니다.([Wikipedia](https://en.wikipedia.org/wiki/Buddhist_calendar)) - To calculate BE year manually, just add 543 to year. For example 26 May 1977 AD/CE should display as 26 May 2520 BE (1977 + 543) @@ -162,43 +168,46 @@ dayjs().format('BBBB BB') List of added formats: -| Format | Output | Description | -| ------ | ---------------- | ------------------------------------- | -| `BBBB` | 2561 | Full BE Year (Year + 543) | -| `BB` | 61 | 2-digit of BE Year | +| Format | Output | Description | +| ------ | ------ | ------------------------- | +| `BBBB` | 2561 | Full BE Year (Year + 543) | +| `BB` | 61 | 2-digit of BE Year | ### IsSameOrAfter - - IsSameOrAfter는 `.isSameOrAfter()` API를 추가하여 날짜가 다른 날짜와 같거나 나중일 경우 `boolean`으로 값을 반환합니다. + +- IsSameOrAfter는 `.isSameOrAfter()` API를 추가하여 날짜가 다른 날짜와 같거나 나중일 경우 `boolean`으로 값을 반환합니다. ```javascript import isSameOrAfter from 'dayjs/plugin/isSameOrAfter' dayjs.extend(isSameOrAfter) -dayjs('2010-10-20').isSameOrAfter('2010-10-19', 'year'); +dayjs('2010-10-20').isSameOrAfter('2010-10-19', 'year') ``` ### IsSameOrBefore - - IsSameOrBefore는 `.isSameOrBefore()` API를 추가하여 날짜가 다른 날짜와 같거나 전일 경우 `boolean`으로 값을 반환합니다. - + +- IsSameOrBefore는 `.isSameOrBefore()` API를 추가하여 날짜가 다른 날짜와 같거나 전일 경우 `boolean`으로 값을 반환합니다. + ```javascript import isSameOrBefore from 'dayjs/plugin/isSameOrBefore' dayjs.extend(isSameOrBefore) -dayjs('2010-10-20').isSameOrBefore('2010-10-19', 'year'); +dayjs('2010-10-20').isSameOrBefore('2010-10-19', 'year') ``` ### IsBetween - - IsBetween은 `.isBetween()` API를 추가하여 두 날짜가 같을 경우 `boolean`으로 값을 반환합니다. + +- IsBetween은 `.isBetween()` API를 추가하여 두 날짜가 같을 경우 `boolean`으로 값을 반환합니다. ```javascript import isBetween from 'dayjs/plugin/isBetween' dayjs.extend(isBetween) -dayjs('2010-10-20').isBetween('2010-10-19', dayjs('2010-10-25'), 'year'); -dayjs('2016-10-30').isBetween('2016-01-01', '2016-10-30', null, '[)'); +dayjs('2010-10-20').isBetween('2010-10-19', dayjs('2010-10-25'), 'year') +dayjs('2016-10-30').isBetween('2016-01-01', '2016-10-30', null, '[)') // '[' indicates inclusion, '(' indicates exclusion ``` @@ -207,16 +216,17 @@ dayjs('2016-10-30').isBetween('2016-01-01', '2016-10-30', null, '[)'); - DayOfYear adds `.dayOfYear()` API to returns a `number` indicating the `Dayjs`'s day of the year, or to set the day of the year. ```javascript -import dayOfYear from "dayjs/plugin/dayOfYear"; +import dayOfYear from 'dayjs/plugin/dayOfYear' -dayjs.extend(dayOfYear); +dayjs.extend(dayOfYear) -dayjs("2010-01-01").dayOfYear(); // 1 -dayjs("2010-01-01").dayOfYear(365); // 2010-12-31 +dayjs('2010-01-01').dayOfYear() // 1 +dayjs('2010-01-01').dayOfYear(365) // 2010-12-31 ``` ### WeekOfYear - - WeekOfYear은 `.week()` API를 추가하여 `Dayjs`의 년의 주를 `number`로 반환 합니다. + +- WeekOfYear은 `.week()` API를 추가하여 `Dayjs`의 년의 주를 `number`로 반환 합니다. ```javascript import weekOfYear from 'dayjs/plugin/weekOfYear' @@ -227,6 +237,7 @@ dayjs('06/27/2018').week() // 26 ``` ### QuarterOfYear + - QuarterOfYear add `.quarter()` API to return to which quarter of the year belongs a date ```javascript @@ -234,11 +245,12 @@ import quarterOfYear from 'dayjs/plugin/quarterOfYear' dayjs.extend(quarterOfYear) -dayjs('2010-04-01').quarter(); // 2 +dayjs('2010-04-01').quarter() // 2 ``` ### CustomParseFormat - - CustomParseFormat extends `dayjs()` constructor to support custom formats of input strings. + +- CustomParseFormat extends `dayjs()` constructor to support custom formats of input strings. To escape characters, wrap them in square brackets (e.g. `[G]`). Punctuation symbols (-:/.()) do not need to be wrapped. @@ -253,29 +265,29 @@ dayjs('05/02/69 1:02:03 PM -05:00', 'MM/DD/YY H:mm:ss A Z') #### List of all available format tokens -| Format | Output | Description | -| ------ | ---------------- | --------------------------------- | -| `YY` | 18 | Two-digit year | -| `YYYY` | 2018 | Four-digit year | -| `M` | 1-12 | Month, beginning at 1 | -| `MM` | 01-12 | Month, 2-digits | -| `D` | 1-31 | Day of month | -| `DD` | 01-31 | Day of month, 2-digits | -| `H` | 0-23 | Hours | -| `HH` | 00-23 | Hours, 2-digits | -| `h` | 1-12 | Hours, 12-hour clock | -| `hh` | 01-12 | Hours, 12-hour clock, 2-digits | -| `m` | 0-59 | Minutes | -| `mm` | 00-59 | Minutes, 2-digits | -| `s` | 0-59 | Seconds | -| `ss` | 00-59 | Seconds, 2-digits | -| `S` | 0-9 | Hundreds of milliseconds, 1-digit | -| `SS` | 00-99 | Tens of milliseconds, 2-digits | -| `SSS` | 000-999 | Milliseconds, 3-digits | -| `Z` | -5:00 | Offset from UTC | -| `ZZ` | -0500 | Compact offset from UTC, 2-digits | -| `A` | AM PM | Post or ante meridiem, upper-case | -| `a` | am pm | Post or ante meridiem, lower-case | +| Format | Output | Description | +| ------ | ------- | --------------------------------- | +| `YY` | 18 | Two-digit year | +| `YYYY` | 2018 | Four-digit year | +| `M` | 1-12 | Month, beginning at 1 | +| `MM` | 01-12 | Month, 2-digits | +| `D` | 1-31 | Day of month | +| `DD` | 01-31 | Day of month, 2-digits | +| `H` | 0-23 | Hours | +| `HH` | 00-23 | Hours, 2-digits | +| `h` | 1-12 | Hours, 12-hour clock | +| `hh` | 01-12 | Hours, 12-hour clock, 2-digits | +| `m` | 0-59 | Minutes | +| `mm` | 00-59 | Minutes, 2-digits | +| `s` | 0-59 | Seconds | +| `ss` | 00-59 | Seconds, 2-digits | +| `S` | 0-9 | Hundreds of milliseconds, 1-digit | +| `SS` | 00-99 | Tens of milliseconds, 2-digits | +| `SSS` | 000-999 | Milliseconds, 3-digits | +| `Z` | -5:00 | Offset from UTC | +| `ZZ` | -0500 | Compact offset from UTC, 2-digits | +| `A` | AM PM | Post or ante meridiem, upper-case | +| `a` | am pm | Post or ante meridiem, lower-case | ## Customize @@ -284,20 +296,21 @@ dayjs('05/02/69 1:02:03 PM -05:00', 'MM/DD/YY H:mm:ss A Z') 플러그인을 제작하고 풀 리퀘스트하여 공유하세요. Day.js 플러그인 템플릿 + ```javascript export default (option, dayjsClass, dayjsFactory) => { // extend dayjs() // e.g. add dayjs().isSameOrBefore() - dayjsClass.prototype.isSameOrBefore = function (arguments) {} + dayjsClass.prototype.isSameOrBefore = function(arguments) {} // extend dayjs // e.g. add dayjs.utc() - dayjsFactory.utc = (arguments) => {} + dayjsFactory.utc = arguments => {} // overriding existing API // e.g. extend dayjs().format() const oldFormat = dayjsClass.prototype.format - dayjsClass.prototype.format = function (arguments) { + dayjsClass.prototype.format = function(arguments) { // original format result const result = oldFormat(arguments) // return modified result diff --git a/docs/ko/README-ko.md b/docs/ko/README-ko.md index 3cfca53b..e24e316c 100644 --- a/docs/ko/README-ko.md +++ b/docs/ko/README-ko.md @@ -24,15 +24,19 @@ > Day.js는 Moment.js와 호환되는 대부분의 API를 사용하며, 최신 브라우저에서 날짜와 시간에 대한 구문 분석, 유효성 검사, 조작, 출력하는 경량 JavaScript 라이브러리입니다. Moment.js를 사용하고 있다면, Day.js는 껌입니다. ```js -dayjs().startOf('month').add(1, 'day').set('year', 2018).format('YYYY-MM-DD HH:mm:ss'); +dayjs() + .startOf('month') + .add(1, 'day') + .set('year', 2018) + .format('YYYY-MM-DD HH:mm:ss') ``` -* 🕒 친숙한 Moment.js API와 패턴 -* 💪 불변 오브젝트(Immutable) -* 🔥 메소드 체인(Chainable) -* 🌐 I18n 지원 -* 📦 2kb 미니 라이브러리 -* 👫 모든 브라우저 지원 +- 🕒 친숙한 Moment.js API와 패턴 +- 💪 불변 오브젝트(Immutable) +- 🔥 메소드 체인(Chainable) +- 🌐 I18n 지원 +- 📦 2kb 미니 라이브러리 +- 👫 모든 브라우저 지원 --- @@ -55,7 +59,9 @@ dayjs('2018-08-08') // parse dayjs().format('{YYYY} MM-DDTHH:mm:ss SSS [Z] A') // display -dayjs().set('month', 3).month() // get & set +dayjs() + .set('month', 3) + .month() // get & set dayjs().add(1, 'year') // manipulate @@ -75,7 +81,9 @@ 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 +dayjs('2018-05-05') + .locale('zh-cn') + .format() // use Chinese Simplified locale in a specific instance ``` 📚[I18n](./I18n.md) @@ -96,4 +104,4 @@ dayjs().format('Q Do k kk X x') // more available formats ## License -Day.js는 [MIT License](./LICENSE)를 사용합니다. +Day.js는 [MIT License](./LICENSE)를 사용합니다. diff --git a/docs/pt-br/API-reference.md b/docs/pt-br/API-reference.md index 18a65f05..9c4715ca 100644 --- a/docs/pt-br/API-reference.md +++ b/docs/pt-br/API-reference.md @@ -65,7 +65,7 @@ O objeto `Dayjs` é imutável, ou seja, todas as operações da API que alteram Chamando este construtor sem parâmetros, será retornado um objeto `Dayjs` contendo a data e hora atual. ```js -dayjs(); +dayjs() ``` Day.js também converte outros formatos de data. @@ -73,19 +73,19 @@ Day.js também converte outros formatos de data. #### string [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) ```js -dayjs('2018-04-04T16:00:00.000Z'); +dayjs('2018-04-04T16:00:00.000Z') ``` #### Objeto `Date` nativo ```js -dayjs(new Date(2018, 8, 18)); +dayjs(new Date(2018, 8, 18)) ``` #### Unix Timestamp (milliseconds) ```js -dayjs(1318781876406); +dayjs(1318781876406) ``` ### Unix Timestamp (seconds) `.unix(value: number)` @@ -93,20 +93,21 @@ dayjs(1318781876406); Returns a `Dayjs` from a Unix timestamp (seconds since the Unix Epoch) ```js -dayjs.unix(1318781876); -dayjs.unix(1318781876.721); +dayjs.unix(1318781876) +dayjs.unix(1318781876.721) ``` ### Custom Parse Format -* parse custom formats `dayjs("12-25-1995", "MM-DD-YYYY")` in plugin [`CustomParseFormat`](./Plugin.md#customparseformat) + +- parse custom formats `dayjs("12-25-1995", "MM-DD-YYYY")` in plugin [`CustomParseFormat`](./Plugin.md#customparseformat) ### Clonar `.clone() | dayjs(original: Dayjs)` Retorna um objeto `Dayjs` clonado. ```js -dayjs().clone(); -dayjs(dayjs('2019-01-25')); // passando um objeto Dayjs para o construtor também irá cloná-lo +dayjs().clone() +dayjs(dayjs('2019-01-25')) // passando um objeto Dayjs para o construtor também irá cloná-lo ``` ### Validação `.isValid()` @@ -114,7 +115,7 @@ dayjs(dayjs('2019-01-25')); // passando um objeto Dayjs para o construtor també Retorna um `boolean` indicando se a data do objeto `Dayjs` é válida. ```js -dayjs().isValid(); +dayjs().isValid() ``` ## Get and Set @@ -124,7 +125,7 @@ dayjs().isValid(); Retorna um `number` representando o ano do objeto `Dayjs`. ```js -dayjs().year(); +dayjs().year() ``` ### Mês `.month()` @@ -132,7 +133,7 @@ dayjs().year(); Retorna um `number` representando o mês do objeto `Dayjs`. ```js -dayjs().month(); +dayjs().month() ``` ### Dia do Mês `.date()` @@ -140,7 +141,7 @@ dayjs().month(); Retorna um `number` representando o dia do mês do objeto `Dayjs`. ```js -dayjs().date(); +dayjs().date() ``` ### Dia da Semana `.day()` @@ -148,7 +149,7 @@ dayjs().date(); Retorna um `number` representando o dia da semana do objeto `Dayjs`. ```js -dayjs().day(); +dayjs().day() ``` ### Hora `.hour()` @@ -156,7 +157,7 @@ dayjs().day(); Retorna um `number` representando a hora do objeto `Dayjs`. ```js -dayjs().hour(); +dayjs().hour() ``` ### Minuto `.minute()` @@ -164,7 +165,7 @@ dayjs().hour(); Retorna um `number` representando os minutos do objeto `Dayjs`. ```js -dayjs().minute(); +dayjs().minute() ``` ### Segundo `.second()` @@ -172,7 +173,7 @@ dayjs().minute(); Retorna um `number` representando os segundos do objeto `Dayjs`. ```js -dayjs().second(); +dayjs().second() ``` ### Milissegundo `.millisecond()` @@ -180,7 +181,7 @@ dayjs().second(); Retorna um `number` representando os milissegundos do objeto `Dayjs`. ```js -dayjs().millisecond(); +dayjs().millisecond() ``` ### Set `.set(unit: string, value: number)` @@ -188,9 +189,9 @@ dayjs().millisecond(); Retorna um `Dayjs` com as mudanças aplicadas. ```js -dayjs().set('date', 1); -dayjs().set('month', 3); // April -dayjs().set('second', 30); +dayjs().set('date', 1) +dayjs().set('month', 3) // April +dayjs().set('second', 30) ``` #### Lista de todas as unidades disponíveis @@ -213,7 +214,8 @@ Um objeto `Dayjs` pode ser manipulado de várias maneiras. ```js dayjs('2019-01-25') .add(1, 'day') - .subtract(1, 'year').toString(); // Fri, 26 Jan 2018 00:00:00 GMT + .subtract(1, 'year') + .toString() // Fri, 26 Jan 2018 00:00:00 GMT ``` ### Adicionar `.add(value: number, unit: string)` @@ -221,7 +223,7 @@ dayjs('2019-01-25') Retorna um objeto `Dayjs` clonado com a quantidade especificada de dias adicionados. ```js -dayjs().add(7, 'day'); +dayjs().add(7, 'day') ``` ### Subtrair `.subtract(value: number, unit: string)` @@ -229,7 +231,7 @@ dayjs().add(7, 'day'); Retorna um objeto `Dayjs` clonado com a quantidade especificada de dias subtraídos. ```js -dayjs().subtract(7, 'year'); +dayjs().subtract(7, 'year') ``` ### Início do Tempo `.startOf(unit: string)` @@ -237,7 +239,7 @@ dayjs().subtract(7, 'year'); Retorna um objeto `Dayjs` clonado definido com o começo da unidade de tempo especificada. ```js -dayjs().startOf('week'); // Depends on `weekStart` in locale +dayjs().startOf('week') // Depends on `weekStart` in locale ``` ### Fim do Tempo `.endOf(unit: string)` @@ -245,7 +247,7 @@ dayjs().startOf('week'); // Depends on `weekStart` in locale Retorna um objeto `Dayjs` clonado definido com o fim da unidade de tempo especificada. ```js -dayjs().endOf('month'); +dayjs().endOf('month') ``` ## Exibindo @@ -256,42 +258,42 @@ Retorna uma `string` com um objeto `Dayjs` contendo a data formatada. Para escapar caracteres, envolva-os entre colchetes ou chaves (por exemplo: `[G] {um}`). ```js -dayjs().format(); // current date in ISO6801, without fraction seconds e.g. '2020-04-02T08:02:17-05:00' +dayjs().format() // current date in ISO6801, without fraction seconds e.g. '2020-04-02T08:02:17-05:00' -dayjs('2019-01-25').format('{YYYY} MM-DDTHH:mm:ssZ[Z]'); // '{2019} 01-25T00:00:00-02:00Z' +dayjs('2019-01-25').format('{YYYY} MM-DDTHH:mm:ssZ[Z]') // '{2019} 01-25T00:00:00-02:00Z' -dayjs('2019-01-25').format('DD/MM/YYYY'); // '25/01/2019' +dayjs('2019-01-25').format('DD/MM/YYYY') // '25/01/2019' ``` #### Lista com todos os formatos disponíveis -| Formato | Saída | Descrição | -| ------ | ---------------- | --------------------------------------------- | -| `YY` | 18 | Ano, com 2 dígitos | -| `YYYY` | 2018 | Ano, com 4 dígitos | -| `M` | 1-12 | Mês (começa em 1) | -| `MM` | 01-12 | Mês, com 2 dígitos | -| `MMM` | Jan-Dec | Nome do mês abreviado | -| `MMMM` | January-December | Nome do mês completo | -| `D` | 1-31 | Dia do mês | -| `DD` | 01-31 | Dia do mês, com 2 dígitos | -| `d` | 0-6 | Dia da semana (Domingo = 0) | -| `dd` | Su-Sa | The min name of the day of the week | -| `ddd` | Sun-Sat | The short name of the day of the week | -| `dddd` | Sunday-Saturday | Nome do dia da semana | -| `H` | 0-23 | Hora | -| `HH` | 00-23 | Hora, com 2 dígitos | -| `h` | 1-12 | Hora (formato de 12 horas) | -| `hh` | 01-12 | Hora, com 2 dígitos (formato de 12 horas) | -| `m` | 0-59 | Minuto | -| `mm` | 00-59 | Minuto, com 2 dígitos | -| `s` | 0-59 | Segundo | -| `ss` | 00-59 | Segundo, com 2 dígitos | -| `SSS` | 000-999 | Milisegundo, com 3 dígitos | -| `Z` | +5:00 | Diferença do fuso horário UTC | -| `ZZ` | +0500 | Diferença do fuso horário UTC, com 2 dígitos | -| `A` | AM PM | | -| `a` | am pm | | +| Formato | Saída | Descrição | +| ------- | ---------------- | -------------------------------------------- | +| `YY` | 18 | Ano, com 2 dígitos | +| `YYYY` | 2018 | Ano, com 4 dígitos | +| `M` | 1-12 | Mês (começa em 1) | +| `MM` | 01-12 | Mês, com 2 dígitos | +| `MMM` | Jan-Dec | Nome do mês abreviado | +| `MMMM` | January-December | Nome do mês completo | +| `D` | 1-31 | Dia do mês | +| `DD` | 01-31 | Dia do mês, com 2 dígitos | +| `d` | 0-6 | Dia da semana (Domingo = 0) | +| `dd` | Su-Sa | The min name of the day of the week | +| `ddd` | Sun-Sat | The short name of the day of the week | +| `dddd` | Sunday-Saturday | Nome do dia da semana | +| `H` | 0-23 | Hora | +| `HH` | 00-23 | Hora, com 2 dígitos | +| `h` | 1-12 | Hora (formato de 12 horas) | +| `hh` | 01-12 | Hora, com 2 dígitos (formato de 12 horas) | +| `m` | 0-59 | Minuto | +| `mm` | 00-59 | Minuto, com 2 dígitos | +| `s` | 0-59 | Segundo | +| `ss` | 00-59 | Segundo, com 2 dígitos | +| `SSS` | 000-999 | Milisegundo, com 3 dígitos | +| `Z` | +5:00 | Diferença do fuso horário UTC | +| `ZZ` | +0500 | Diferença do fuso horário UTC, com 2 dígitos | +| `A` | AM PM | | +| `a` | am pm | | - Mais formatos disponíveis `Q Do k kk X x ...` no plugin [`AdvancedFormat`](./Plugin.md#advancedformat) - Localized format options `L LT LTS ...` in plugin [`LocalizedFormat`](./Plugin.md#localizedFormat) @@ -301,12 +303,12 @@ dayjs('2019-01-25').format('DD/MM/YYYY'); // '25/01/2019' Retorna um `number` indicando a diferença entre dois objetos `Dayjs` na unidade especificada. ```js -const date1 = dayjs('2019-01-25'); -const date2 = dayjs('2018-06-05'); -date1.diff(date2); // 20214000000 -date1.diff(date2, 'month'); // 7 -date1.diff(date2, 'month', true); // 7.645161290322581 -date1.diff(date2, 'day'); // 233 +const date1 = dayjs('2019-01-25') +const date2 = dayjs('2018-06-05') +date1.diff(date2) // 20214000000 +date1.diff(date2, 'month') // 7 +date1.diff(date2, 'month', true) // 7.645161290322581 +date1.diff(date2, 'day') // 233 ``` ### Unix Timestamp (milissegundos) `.valueOf()` @@ -314,7 +316,7 @@ date1.diff(date2, 'day'); // 233 Retorna um `number` em milissegundos desde a Unix Epoch para o objeto `Dayjs`. ```js -dayjs('2019-01-25').valueOf(); // 1548381600000 +dayjs('2019-01-25').valueOf() // 1548381600000 ``` ### Unix Timestamp (segundos) `.unix()` @@ -322,7 +324,7 @@ dayjs('2019-01-25').valueOf(); // 1548381600000 Retorna um `number` em segundos desde a Unix Epoch para o objeto `Dayjs`. ```js -dayjs('2019-01-25').unix(); // 1548381600 +dayjs('2019-01-25').unix() // 1548381600 ``` ### UTC Offset (minutes) `.utcOffset()` @@ -330,7 +332,7 @@ dayjs('2019-01-25').unix(); // 1548381600 Returns the UTC offset in minutes for the `Dayjs`. ```js -dayjs().utcOffset(); +dayjs().utcOffset() ``` ### Dias no Mês `.daysInMonth()` @@ -338,7 +340,7 @@ dayjs().utcOffset(); Retorna um `number` em contendo o número de dias no mês do objeto `Dayjs`. ```js -dayjs('2019-01-25').daysInMonth(); // 31 +dayjs('2019-01-25').daysInMonth() // 31 ``` ### Como objeto `Date` do Javascript `.toDate()` @@ -346,7 +348,7 @@ dayjs('2019-01-25').daysInMonth(); // 31 Retorna uma cópia do objeto nativo `Date` convertido de um objeto `Dayjs`. ```js -dayjs('2019-01-25').toDate(); +dayjs('2019-01-25').toDate() ``` ### Como Array `.toArray()` @@ -354,7 +356,7 @@ dayjs('2019-01-25').toDate(); Retorna um `array` que espelha os parâmetros de um new Date(). ```js -dayjs('2019-01-25').toArray(); // [ 2019, 0, 25, 0, 0, 0, 0 ] +dayjs('2019-01-25').toArray() // [ 2019, 0, 25, 0, 0, 0, 0 ] ``` ### Como JSON `.toJSON()` @@ -362,7 +364,7 @@ dayjs('2019-01-25').toArray(); // [ 2019, 0, 25, 0, 0, 0, 0 ] Retorna o objeto `Dayjs` formatado em uma `string` ISO8601. ```js -dayjs('2019-01-25').toJSON(); // '2019-01-25T02:00:00.000Z' +dayjs('2019-01-25').toJSON() // '2019-01-25T02:00:00.000Z' ``` ### Como uma string ISO 8601 `.toISOString()` @@ -370,7 +372,7 @@ dayjs('2019-01-25').toJSON(); // '2019-01-25T02:00:00.000Z' Retorna o objeto `Dayjs` formatado em uma `string` ISO8601. ```js -dayjs('2019-01-25').toISOString(); // '2019-01-25T02:00:00.000Z' +dayjs('2019-01-25').toISOString() // '2019-01-25T02:00:00.000Z' ``` ### Como Objeto `.toObject()` @@ -378,7 +380,7 @@ dayjs('2019-01-25').toISOString(); // '2019-01-25T02:00:00.000Z' Retorna um `object` com as propriedades da data. ```js -dayjs('2019-01-25').toObject(); +dayjs('2019-01-25').toObject() /* { years: 2019, months: 0, date: 25, @@ -390,10 +392,10 @@ dayjs('2019-01-25').toObject(); ### Como String `.toString()` -Retorna uma representação em `string` da data. +Retorna uma representação em `string` da data. ```js -dayjs('2019-01-25').toString(); // 'Fri, 25 Jan 2019 02:00:00 GMT' +dayjs('2019-01-25').toString() // 'Fri, 25 Jan 2019 02:00:00 GMT' ``` ## Consulta @@ -403,8 +405,8 @@ dayjs('2019-01-25').toString(); // 'Fri, 25 Jan 2019 02:00:00 GMT' Retorna um `boolean` indicando se a data do objeto `Dayjs` é antes da data fornecida de em outro objeto `Dayjs`. ```js -dayjs().isBefore(dayjs()); // false -dayjs().isBefore(dayjs(), 'year'); // false +dayjs().isBefore(dayjs()) // false +dayjs().isBefore(dayjs(), 'year') // false ``` ### Igual `.isSame(compared: Dayjs, unit?: string)`] @@ -412,8 +414,8 @@ dayjs().isBefore(dayjs(), 'year'); // false Retorna um `boolean` indicando se a data do objeto `Dayjs` é a mesma data fornecida de em outro objeto `Dayjs`. ```js -dayjs().isSame(dayjs()); // true -dayjs().isSame(dayjs(), 'year'); // true +dayjs().isSame(dayjs()) // true +dayjs().isSame(dayjs(), 'year') // true ``` ### Depois `.isAfter(compared: Dayjs, unit?: string)`] @@ -421,8 +423,8 @@ dayjs().isSame(dayjs(), 'year'); // true Retorna um `boolean` indicando se a data do objeto `Dayjs` é depois da data fornecida de em outro objeto `Dayjs`. ```js -dayjs().isAfter(dayjs()); // false -dayjs().isAfter(dayjs(), 'year'); // false +dayjs().isAfter(dayjs()) // false +dayjs().isAfter(dayjs(), 'year') // false ``` ### É um objeto `Dayjs` `.isDayjs()` @@ -430,8 +432,8 @@ dayjs().isAfter(dayjs(), 'year'); // false Retorna um `boolean` indicando se a variável é um objeto `Dayjs` ou não. ```js -dayjs.isDayjs(dayjs()); // true -dayjs.isDayjs(new Date()); // false +dayjs.isDayjs(dayjs()) // true +dayjs.isDayjs(new Date()) // false ``` The operator `instanceof` works equally well: diff --git a/docs/pt-br/I18n.md b/docs/pt-br/I18n.md index 23079be6..10826352 100644 --- a/docs/pt-br/I18n.md +++ b/docs/pt-br/I18n.md @@ -2,21 +2,21 @@ Day.js possui um ótimo suporte para internacionalização. -Porém nenhuma delas estarão incluídas no seu *build* até que você as utilize. +Porém nenhuma delas estarão incluídas no seu _build_ até que você as utilize. -Por padrão, Day.js vem com o *locale* Inglês (Estados Unidos). +Por padrão, Day.js vem com o _locale_ Inglês (Estados Unidos). -Você pode carregar múltiplos *locales* e alternar entre eles facilmente. +Você pode carregar múltiplos _locales_ e alternar entre eles facilmente. [Lista de locales disponíveis](../../src/locale) -Você será bem-vindo para adicionar um *locale* abrindo um pull request. :+1: +Você será bem-vindo para adicionar um _locale_ abrindo um pull request. :+1: ## API #### Mudando locale globalmente -* Retorna uma string com o locale global +- Retorna uma string com o locale global ```js import 'dayjs/locale/es' @@ -28,23 +28,25 @@ dayjs.locale(customizedLocaleObject) // usar locale customizado dayjs.locale('en') // switch back to default English locale globally ``` -* Mudar o *locale* global não afeta instâncias já existentes. +- Mudar o _locale_ global não afeta instâncias já existentes. -#### Mudar *locales* localmente +#### Mudar _locales_ localmente -* Retorna um novo objeto `Dayjs` para ser substituído por um novo *locale* +- Retorna um novo objeto `Dayjs` para ser substituído por um novo _locale_ -Exatamente o mesmo que `dayjs#locale`, porém utilizando somente o *locale* em uma instâcia específica. +Exatamente o mesmo que `dayjs#locale`, porém utilizando somente o _locale_ em uma instâcia específica. ```js import 'dayjs/locale/es' -dayjs().locale('es').format() // usar locale localmente +dayjs() + .locale('es') + .format() // usar locale localmente dayjs('2018-4-28', { locale: 'es' }) // também pode ser feito no constructor ``` ## Instalação -* Via NPM: +- Via NPM: ```javascript import 'dayjs/locale/es' // carregar locale es @@ -52,17 +54,22 @@ import 'dayjs/locale/es' // carregar locale es // import locale_es from 'dayjs/locale/es' -> carregar e obter objeto locale locale_es dayjs.locale('es') // usar locale globalmente -dayjs().locale('es').format() // usar locale em uma instância específica +dayjs() + .locale('es') + .format() // usar locale em uma instância específica ``` -* Via CDN: +- Via CDN: + ```html @@ -70,11 +77,12 @@ dayjs().locale('es').format() // usar locale em uma instância específica ## Customizar -Você pode criar o seu próprio *locale*. +Você pode criar o seu próprio _locale_. + +Sinta-se a vontade para abrir uma pull request e compartilhar sua _locale_. -Sinta-se a vontade para abrir uma pull request e compartilhar sua *locale*. +Modelo de um objeto _locale_ Day.js. -Modelo de um objeto *locale* Day.js. ```javascript const objetoLocale = { name: 'es', // nome: String @@ -85,7 +93,8 @@ const objetoLocale = { months: 'Enero_Febrero ... '.split('_'), // meses: Array monthsShort: 'Jan_F'.split('_'), // OPCIONAL, meses com nome curto: Array, utiliza as três primeiras letras se nenhuma for especificada ordinal: n => `${n}º`, // ordinal: Function (number) => retorna number + saída - relativeTime: { // formato relativo de horas, mantém %s %d como o mesmo + relativeTime: { + // formato relativo de horas, mantém %s %d como o mesmo future: 'em %s', // exemplo: em 2 horas, %s será substituído por 2 horas past: '%s ago', s: 'a few seconds', @@ -103,7 +112,8 @@ const objetoLocale = { } ``` -Modelo de um arquivo *locale* do Day.js. +Modelo de um arquivo _locale_ do Day.js. + ```javascript import dayjs from 'dayjs' @@ -112,4 +122,4 @@ const locale = { ... } // seu objeto de locale dayjs.locale(locale, null, true) // carregar locale para uso posterior export default locale -``` \ No newline at end of file +``` diff --git a/docs/pt-br/Installation.md b/docs/pt-br/Installation.md index 4fc95a51..da648129 100644 --- a/docs/pt-br/Installation.md +++ b/docs/pt-br/Installation.md @@ -2,7 +2,7 @@ Existem várias maneiras de incluir o Day.js em seu projeto: -* Via NPM: +- Via NPM: ```console npm install dayjs --save @@ -12,19 +12,19 @@ npm install dayjs --save import dayjs from 'dayjs' // Ou se preferir CommonJS // var dayjs = require('dayjs'); -dayjs().format(); +dayjs().format() ``` -* Via CDN: +- Via CDN: ```html ``` -* Via download e *self-hosting*: +- Via download e _self-hosting_: -Simplesmente baixe a última versão do Day.js: [https://unpkg.com/dayjs/](https://unpkg.com/dayjs/) \ No newline at end of file +Simplesmente baixe a última versão do Day.js: [https://unpkg.com/dayjs/](https://unpkg.com/dayjs/) diff --git a/docs/pt-br/Plugin.md b/docs/pt-br/Plugin.md index 6c2d9dbb..0d600048 100644 --- a/docs/pt-br/Plugin.md +++ b/docs/pt-br/Plugin.md @@ -2,7 +2,7 @@ Um plugin é um módulo independente que pode ser adicionado ao Day.js para estendê-lo ou adicionar novas funcionalidades. -Por padrão, o Day.js vem somente com seu código *core* e sem plugins instalados. +Por padrão, o Day.js vem somente com seu código _core_ e sem plugins instalados. Você pode adicionar múltiplos plugins de acordo com a sua necessidade. @@ -10,7 +10,7 @@ Você pode adicionar múltiplos plugins de acordo com a sua necessidade. #### Extend -* Retorna objeto Dayjs +- Retorna objeto Dayjs Usando um plugin. @@ -22,7 +22,7 @@ dayjs.extend(plugin, options) // com opções do plugin ## Instalação -* Via NPM: +- Via NPM: ```javascript import dayjs from 'dayjs' @@ -31,20 +31,22 @@ import advancedFormat from 'dayjs/plugin/advancedFormat' // carregar sob demanda dayjs.extend(advancedFormat) // usa o plugin ``` -* Via CDN: +- Via CDN: + ```html ``` ## Lista de plugins oficiais ### AdvancedFormat - - O AdvancedFormat estende a API de `dayjs().format` para fornecer mais opções de formatação. + +- O AdvancedFormat estende a API de `dayjs().format` para fornecer mais opções de formatação. ```javascript import AdvancedFormat from 'dayjs/plugin/advancedFormat' @@ -56,17 +58,18 @@ dayjs().format('Q Do k kk X x') Lista de formatos adicionados: -| Formato | Saída | Descrição | -| ------- | ---------------- | ------------------------------------- | -| `Q` | 1-4 | Quarter | -| `Do` | 1st 2nd ... 31st | Dia do mês com ordinal | -| `k` | 1-23 | Hora (começando do 1) | -| `kk` | 01-23 | Hora, com 2 dígitos (começando do 1) | -| `X` | 1360013296 | Unix Timestamp em segundos | -| `x` | 1360013296123 | Unix Timestamp em milissegundos | +| Formato | Saída | Descrição | +| ------- | ---------------- | ------------------------------------ | +| `Q` | 1-4 | Quarter | +| `Do` | 1st 2nd ... 31st | Dia do mês com ordinal | +| `k` | 1-23 | Hora (começando do 1) | +| `kk` | 01-23 | Hora, com 2 dígitos (começando do 1) | +| `X` | 1360013296 | Unix Timestamp em segundos | +| `x` | 1360013296123 | Unix Timestamp em milissegundos | ### LocalizedFormat - - LocalizedFormat extends `dayjs().format` API to supply localized format options. + +- LocalizedFormat extends `dayjs().format` API to supply localized format options. ```javascript import LocalizedFormat from 'dayjs/plugin/localizedFormat' @@ -88,7 +91,8 @@ List of added formats: | `LLLL` | dddd, MMMM D, YYYY h:mm A | Thursday, August 16, 2018 8:02 PM | ### RelativeTime - - RelativeTime adds `.from` `.to` `.fromNow` `.toNow` APIs to formats date to relative time strings (e.g. 3 hours ago). + +- RelativeTime adds `.from` `.to` `.fromNow` `.toNow` APIs to formats date to relative time strings (e.g. 3 hours ago). ```javascript import relativeTime from 'dayjs/plugin/relativeTime' @@ -109,7 +113,7 @@ dayjs().toNow() Retorna uma `string` do tempo relativo a partir de agora. -#### Tempo a partir de X `.from(compared: Dayjs, withoutSuffix?: boolean)` +#### Tempo a partir de X `.from(compared: Dayjs, withoutSuffix?: boolean)` Retorna uma `string` do tempo relativo a partir de X. @@ -117,36 +121,38 @@ Retorna uma `string` do tempo relativo a partir de X. Retorna uma `string` do tempo relativo até agora. -#### Tempo até X `.to(compared: Dayjs, withoutSuffix?: boolean)` +#### Tempo até X `.to(compared: Dayjs, withoutSuffix?: boolean)` Retorna uma `string` do tempo relativo até X. -| Intervalo | Chave | Sample Output | -| ------------------------ | ------ | -------------------------------- | -| 0 to 44 seconds | s | a few seconds ago | -| 45 to 89 seconds | m | a minute ago | -| 90 seconds to 44 minutes | mm | 2 minutes ago ... 44 minutes ago | -| 45 to 89 minutes | h | an hour ago | -| 90 minutes to 21 hours | hh | 2 hours ago ... 21 hours ago | -| 22 to 35 hours | d | a day ago | -| 36 hours to 25 days | dd | 2 days ago ... 25 days ago | -| 26 to 45 days | M | a month ago | -| 46 days to 10 months | MM | 2 months ago ... 10 months ago | -| 11 months to 17months | y | a year ago | -| 18 months+ | yy | 2 years ago ... 20 years ago | +| Intervalo | Chave | Sample Output | +| ------------------------ | ----- | -------------------------------- | +| 0 to 44 seconds | s | a few seconds ago | +| 45 to 89 seconds | m | a minute ago | +| 90 seconds to 44 minutes | mm | 2 minutes ago ... 44 minutes ago | +| 45 to 89 minutes | h | an hour ago | +| 90 minutes to 21 hours | hh | 2 hours ago ... 21 hours ago | +| 22 to 35 hours | d | a day ago | +| 36 hours to 25 days | dd | 2 days ago ... 25 days ago | +| 26 to 45 days | M | a month ago | +| 46 days to 10 months | MM | 2 months ago ... 10 months ago | +| 11 months to 17months | y | a year ago | +| 18 months+ | yy | 2 years ago ... 20 years ago | ### IsLeapYear - - IsLeapYear adiciona `.isLeapYear` à API para retornar um `boolean` indicando se o objeto `Dayjs` é um ano bissexto ou não. + +- IsLeapYear adiciona `.isLeapYear` à API para retornar um `boolean` indicando se o objeto `Dayjs` é um ano bissexto ou não. ```javascript import isLeapYear from 'dayjs/plugin/isLeapYear' dayjs.extend(isLeapYear) -dayjs('2000-01-01').isLeapYear(); // true +dayjs('2000-01-01').isLeapYear() // true ``` ### BuddhistEra + - BuddhistEra estende a API `dayjs().format` para fornecer opções de formação da era Budista (B.E.). - A era Budista é um sistema de numeração do ano que se usou primeiramente em países asiáticos do Sudeste Asiático de Cambodia, de Laos, de Myanmar e da Tailândia, assim como em Sri Lanka e em populações chinesas da Malaysia e de Cingapura para ocasiões religiosas ou oficiais [Wikipedia](https://en.wikipedia.org/wiki/Buddhist_calendar)) - Para calcular um ano da era Budista manualmente, apenas adicione 543 ao ano. Por exemplo, 26 de maio de 1977 AD/CE deverá ser exibido como 26 de maio de 2520 BE (1977 + 543). @@ -161,60 +167,65 @@ dayjs().format('BBBB BB') Lista de formatos adicionados: -| Formato | Saída | Descrição | -| ------- | ---------------- | ------------------------------------- | -| `BBBB` | 2561 | Full BE Year (Year + 543) | -| `BB` | 61 | 2-digit of BE Year | +| Formato | Saída | Descrição | +| ------- | ----- | ------------------------- | +| `BBBB` | 2561 | Full BE Year (Year + 543) | +| `BB` | 61 | 2-digit of BE Year | ### IsSameOrAfter - - IsSameOrAfter adds `.isSameOrAfter()` API to returns a `boolean` indicating if a date is same of after another date. + +- IsSameOrAfter adds `.isSameOrAfter()` API to returns a `boolean` indicating if a date is same of after another date. ```javascript import isSameOrAfter from 'dayjs/plugin/isSameOrAfter' dayjs.extend(isSameOrAfter) -dayjs('2010-10-20').isSameOrAfter('2010-10-19', 'year'); +dayjs('2010-10-20').isSameOrAfter('2010-10-19', 'year') ``` ### IsSameOrBefore - - IsSameOrBefore adds `.isSameOrBefore()` API to returns a `boolean` indicating if a date is same of before another date. + +- IsSameOrBefore adds `.isSameOrBefore()` API to returns a `boolean` indicating if a date is same of before another date. ```javascript import isSameOrBefore from 'dayjs/plugin/isSameOrBefore' dayjs.extend(isSameOrBefore) -dayjs('2010-10-20').isSameOrBefore('2010-10-19', 'year'); +dayjs('2010-10-20').isSameOrBefore('2010-10-19', 'year') ``` ### IsBetween - - IsBetween adiciona `.isBetween()` à API para retornar um `boolean` indicando se a data está entre outras duas datas. + +- IsBetween adiciona `.isBetween()` à API para retornar um `boolean` indicando se a data está entre outras duas datas. ```javascript import isBetween from 'dayjs/plugin/isBetween' dayjs.extend(isBetween) -dayjs('2010-10-20').isBetween('2010-10-19', dayjs('2010-10-25'), 'year'); -dayjs('2016-10-30').isBetween('2016-01-01', '2016-10-30', null, '[)'); +dayjs('2010-10-20').isBetween('2010-10-19', dayjs('2010-10-25'), 'year') +dayjs('2016-10-30').isBetween('2016-01-01', '2016-10-30', null, '[)') // '[' indicates inclusion, '(' indicates exclusion ``` + ### DayOfYear - DayOfYear adds `.dayOfYear()` API to returns a `number` indicating the `Dayjs`'s day of the year, or to set the day of the year. ```javascript -import dayOfYear from "dayjs/plugin/dayOfYear"; +import dayOfYear from 'dayjs/plugin/dayOfYear' -dayjs.extend(dayOfYear); +dayjs.extend(dayOfYear) -dayjs("2010-01-01").dayOfYear(); // 1 -dayjs("2010-01-01").dayOfYear(365); // 2010-12-31 +dayjs('2010-01-01').dayOfYear() // 1 +dayjs('2010-01-01').dayOfYear(365) // 2010-12-31 ``` ### WeekOfYear - - WeekOfYear adiciona `.week()` à API para retornar um `number` indicando um objeto `Dayjs` com a semana do ano.. + +- WeekOfYear adiciona `.week()` à API para retornar um `number` indicando um objeto `Dayjs` com a semana do ano.. ```javascript import weekOfYear from 'dayjs/plugin/weekOfYear' @@ -225,6 +236,7 @@ dayjs('06/27/2018').week() // 26 ``` ### QuarterOfYear + - QuarterOfYear add `.quarter()` API to return to which quarter of the year belongs a date ```javascript @@ -232,11 +244,12 @@ import quarterOfYear from 'dayjs/plugin/quarterOfYear' dayjs.extend(quarterOfYear) -dayjs('2010-04-01').quarter(); // 2 +dayjs('2010-04-01').quarter() // 2 ``` ### CustomParseFormat - - CustomParseFormat extends `dayjs()` constructor to support custom formats of input strings. + +- CustomParseFormat extends `dayjs()` constructor to support custom formats of input strings. To escape characters, wrap them in square brackets (e.g. `[G]`). Punctuation symbols (-:/.()) do not need to be wrapped. @@ -251,29 +264,29 @@ dayjs('05/02/69 1:02:03 PM -05:00', 'MM/DD/YY H:mm:ss A Z') #### List of all available format tokens -| Format | Output | Description | -| ------ | ---------------- | --------------------------------- | -| `YY` | 18 | Two-digit year | -| `YYYY` | 2018 | Four-digit year | -| `M` | 1-12 | Month, beginning at 1 | -| `MM` | 01-12 | Month, 2-digits | -| `D` | 1-31 | Day of month | -| `DD` | 01-31 | Day of month, 2-digits | -| `H` | 0-23 | Hours | -| `HH` | 00-23 | Hours, 2-digits | -| `h` | 1-12 | Hours, 12-hour clock | -| `hh` | 01-12 | Hours, 12-hour clock, 2-digits | -| `m` | 0-59 | Minutes | -| `mm` | 00-59 | Minutes, 2-digits | -| `s` | 0-59 | Seconds | -| `ss` | 00-59 | Seconds, 2-digits | -| `S` | 0-9 | Hundreds of milliseconds, 1-digit | -| `SS` | 00-99 | Tens of milliseconds, 2-digits | -| `SSS` | 000-999 | Milliseconds, 3-digits | -| `Z` | -5:00 | Offset from UTC | -| `ZZ` | -0500 | Compact offset from UTC, 2-digits | -| `A` | AM PM | Post or ante meridiem, upper-case | -| `a` | am pm | Post or ante meridiem, lower-case | +| Format | Output | Description | +| ------ | ------- | --------------------------------- | +| `YY` | 18 | Two-digit year | +| `YYYY` | 2018 | Four-digit year | +| `M` | 1-12 | Month, beginning at 1 | +| `MM` | 01-12 | Month, 2-digits | +| `D` | 1-31 | Day of month | +| `DD` | 01-31 | Day of month, 2-digits | +| `H` | 0-23 | Hours | +| `HH` | 00-23 | Hours, 2-digits | +| `h` | 1-12 | Hours, 12-hour clock | +| `hh` | 01-12 | Hours, 12-hour clock, 2-digits | +| `m` | 0-59 | Minutes | +| `mm` | 00-59 | Minutes, 2-digits | +| `s` | 0-59 | Seconds | +| `ss` | 00-59 | Seconds, 2-digits | +| `S` | 0-9 | Hundreds of milliseconds, 1-digit | +| `SS` | 00-99 | Tens of milliseconds, 2-digits | +| `SSS` | 000-999 | Milliseconds, 3-digits | +| `Z` | -5:00 | Offset from UTC | +| `ZZ` | -0500 | Compact offset from UTC, 2-digits | +| `A` | AM PM | Post or ante meridiem, upper-case | +| `a` | am pm | Post or ante meridiem, lower-case | ## Customizar @@ -282,23 +295,24 @@ Você também pode construir seu próprio plugin Day.js para diferentes necessid Sinta-se à vontade para abrir um pull request e compartilhar seu plugin. Modelo de um plugin Day.js. + ```javascript export default (option, dayjsClass, dayjsFactory) => { // estender dayjs() // ex: adicionar dayjs().isSameOrBefore() - dayjsClass.prototype.isSameOrBefore = function (arguments) {} + dayjsClass.prototype.isSameOrBefore = function(arguments) {} // estender dayjs // ex: adicionar dayjs.utc() - dayjsFactory.utc = (arguments) => {} + dayjsFactory.utc = arguments => {} // sobrescrever API existente // ex: estender dayjs().format() const formatoAntigo = dayjsClass.prototype.format - dayjsClass.prototype.format = function (arguments) { + dayjsClass.prototype.format = function(arguments) { // original const result = formatoAntigo(arguments) // retornar modificado } } -``` \ No newline at end of file +``` diff --git a/docs/pt-br/README-pt-br.md b/docs/pt-br/README-pt-br.md index f818f658..06fd9726 100644 --- a/docs/pt-br/README-pt-br.md +++ b/docs/pt-br/README-pt-br.md @@ -24,15 +24,19 @@ > Day.js é uma biblioteca JavaScript minimalista que analisa, valida, manipula e formata datas e horas para navegadores modernos, usando uma API quase completamente compatível com Moment.js. Se você já usou Moment.js, já sabe usar Day.js. ```js -dayjs().startOf('month').add(1, 'day').set('year', 2018).format('YYYY-MM-DD HH:mm:ss'); +dayjs() + .startOf('month') + .add(1, 'day') + .set('year', 2018) + .format('YYYY-MM-DD HH:mm:ss') ``` -* 🕒 API & padrões familiares aos do Moment.js -* 💪 Imutável -* 🔥 Encadeável -* 🌐 Suporta I18n -* 📦 Mini biblioteca de 2kb -* 👫 Suporta todos os navegadores +- 🕒 API & padrões familiares aos do Moment.js +- 💪 Imutável +- 🔥 Encadeável +- 🌐 Suporta I18n +- 📦 Mini biblioteca de 2kb +- 👫 Suporta todos os navegadores --- @@ -55,7 +59,9 @@ dayjs('2018-08-08') // converte dayjs().format('{YYYY} MM-DDTHH:mm:ss SSS [Z] A') // formata -dayjs().set('month', 3).month() // get & set +dayjs() + .set('month', 3) + .month() // get & set dayjs().add(1, 'year') // manipula @@ -68,15 +74,18 @@ dayjs().isBefore(dayjs()) // verifica Day.js tem suporte para internacionalização. -Porém nenhuma estará inclusa no seu *build* a menos que você utilize-a. +Porém nenhuma estará inclusa no seu _build_ a menos que você utilize-a. ```javascript import 'dayjs/locale/es' // carregar sob demanda dayjs.locale('es') // usar locale espanhol globalmente -dayjs('2018-05-05').locale('pt-br').format() // usar locale em português brasileiro em uma instância específica +dayjs('2018-05-05') + .locale('pt-br') + .format() // usar locale em português brasileiro em uma instância específica ``` + 📚[Internacionalização](./I18n.md) ### Plugin @@ -107,9 +116,9 @@ Este projeto existe graças a todas as pessoas que contribuem. Por favor, nos dê uma 💖 estrela 💖 para suportar-nos. Obrigado. -E obrigado a todos os nossos apoiadores! 🙏 +E obrigado a todos os nossos apoiadores! 🙏 ## Licença -Day.js é licenciado sob a [MIT License](../../LICENSE). \ No newline at end of file +Day.js é licenciado sob a [MIT License](../../LICENSE). diff --git a/docs/zh-cn/API-reference.md b/docs/zh-cn/API-reference.md index 3f5f5e3c..76e14c3c 100644 --- a/docs/zh-cn/API-reference.md +++ b/docs/zh-cn/API-reference.md @@ -4,173 +4,224 @@ `Dayjs` 对象是不可变的, 所有的 API 操作都将返回一个新的 `Dayjs` 对象。 -* [解析](#解析) - * [当前时间](#当前时间) - * [时间字符串](#时间字符串) - * [Date 对象](#date-对象) - * [Unix 时间戳 (毫秒)](#unix-时间戳-毫秒) - * [Unix 时间戳 (秒)](#unix-时间戳-秒) - * [自定义时间格式](#自定义时间格式) - * [复制](#复制) - * [验证](#验证) -* [获取+设置](#获取设置) - * [年](#年) - * [月](#月) - * [日](#日) - * [星期](#星期) - * [时](#时) - * [分](#分) - * [秒](#秒) - * [毫秒](#毫秒) - * [设置](#设置) -* [操作](#操作) - * [增加](#增加) - * [减少](#减少) - * [开头时间](#开头时间) - * [末尾时间](#末尾时间) -* [显示](#显示) - * [格式化](#格式化) - * [时间差](#时间差) - * [Unix 时间戳 (毫秒)](#unix-时间戳-毫秒-1) - * [Unix 时间戳 (秒)](#unix-时间戳-秒) - - [UTC 偏移量 (分)](#utc-偏移量-分) - * [天数 (月)](#天数-月) - * [Date 对象](#date-对象-1) - * [数组](#数组) - * [JSON](#as-json) - * [ISO 8601 字符串](#iso-8601-字符串) - * [对象](#对象) - * [字符串](#字符串) -* [查询](#查询) - * [是否之前](#是否之前) - * [是否相同](#是否相同) - * [是否之后](#是否之后) - * [是否是 Dayjs `.isDayjs()`](#是否是-dayjs-isdayjscompared-any) -* [插件 APIs](#plugin-apis) - * [相对时间](#relativetime) - * [是否是闰年](#是否是闰年) - * [年中的第几周](#年中的第几周) - * [是否相同或之后](#是否相同或之后) - * [是否相同或之前](#是否相同或之前) - * [是否之间](#是否之间) - * [年中第几季度](#年中第几季度) +- [解析](#解析) + - [当前时间](#当前时间) + - [时间字符串](#时间字符串) + - [Date 对象](#date-对象) + - [Unix 时间戳 (毫秒)](#unix-时间戳-毫秒) + - [Unix 时间戳 (秒)](#unix-时间戳-秒) + - [自定义时间格式](#自定义时间格式) + - [复制](#复制) + - [验证](#验证) +- [获取+设置](#获取设置) + - [年](#年) + - [月](#月) + - [日](#日) + - [星期](#星期) + - [时](#时) + - [分](#分) + - [秒](#秒) + - [毫秒](#毫秒) + - [设置](#设置) +- [操作](#操作) + - [增加](#增加) + - [减少](#减少) + - [开头时间](#开头时间) + - [末尾时间](#末尾时间) +- [显示](#显示) + - [格式化](#格式化) + - [时间差](#时间差) + - [Unix 时间戳 (毫秒)](#unix-时间戳-毫秒-1) + - [Unix 时间戳 (秒)](#unix-时间戳-秒) + * [UTC 偏移量 (分)](#utc-偏移量-分) + - [天数 (月)](#天数-月) + - [Date 对象](#date-对象-1) + - [数组](#数组) + - [JSON](#as-json) + - [ISO 8601 字符串](#iso-8601-字符串) + - [对象](#对象) + - [字符串](#字符串) +- [查询](#查询) + - [是否之前](#是否之前) + - [是否相同](#是否相同) + - [是否之后](#是否之后) + - [是否是 Dayjs `.isDayjs()`](#是否是-dayjs-isdayjscompared-any) +- [插件 APIs](#plugin-apis) + - [相对时间](#relativetime) + - [是否是闰年](#是否是闰年) + - [年中的第几周](#年中的第几周) + - [是否相同或之后](#是否相同或之后) + - [是否相同或之前](#是否相同或之前) + - [是否之间](#是否之间) + - [年中第几季度](#年中第几季度) --- + 如果没有特别说明,Day.js 的返回值都是新的 `Dayjs` 对象。 ### 解析 + 在 `dayjs()` 中传入支持的格式 + #### 当前时间 + 直接运行 `dayjs()`,得到包含当前时间和日期的 `Dayjs` 对象。 + ```js -dayjs(); +dayjs() ``` + ### 时间字符串 + 可以解析传入的一个标准的[ISO 8601](https://en.wikipedia.org/wiki/ISO_8601)时间字符串。 + ```js -dayjs(String); -dayjs("1995-12-25"); +dayjs(String) +dayjs('1995-12-25') ``` + ### Date 对象 + 可以解析传入的一个 Javascript Date 对象。 + ```js -dayjs(Date); -dayjs(new Date(2018, 8, 18)); +dayjs(Date) +dayjs(new Date(2018, 8, 18)) ``` ### Unix 时间戳 (毫秒) -可以解析传入的一个 Unix 时间戳 (13位数字)。 + +可以解析传入的一个 Unix 时间戳 (13 位数字)。 + ```js -dayjs(Number); -dayjs(1318781876406); +dayjs(Number) +dayjs(1318781876406) ``` ### Unix 时间戳 (秒) -可以解析传入的一个 Unix 时间戳 (10位数字)。 + +可以解析传入的一个 Unix 时间戳 (10 位数字)。 + ```js -dayjs.unix(Number); -dayjs.unix(1318781876); +dayjs.unix(Number) +dayjs.unix(1318781876) ``` ### 自定义时间格式 -* 解析自定义时间格式如 `dayjs("12-25-1995", "MM-DD-YYYY")` 可以使用插件 [`CustomParseFormat`](./Plugin.md#customparseformat) + +- 解析自定义时间格式如 `dayjs("12-25-1995", "MM-DD-YYYY")` 可以使用插件 [`CustomParseFormat`](./Plugin.md#customparseformat) ### 复制 + `Dayjs` 对象是不可变的,如果您想获得一个对象的拷贝,请执行 `.clone()`。 向 `dayjs()` 里传入一个 `Dayjs` 对象也能实现同样的效果。 + ```js -dayjs(Dayjs); -dayjs().clone(); +dayjs(Dayjs) +dayjs().clone() ``` + ### 验证 + - return Boolean 检测当前 `Dayjs` 对象是否是一个有效的时间。 + ```js -dayjs().isValid(); +dayjs().isValid() ``` + --- + ### 获取+设置 + 获取和改变日期。 + #### 年 + - return Number 获取年份。 + ```js -dayjs().year(); +dayjs().year() ``` + #### 月 + - return Number 获取月份。 + ```js -dayjs().month(); +dayjs().month() ``` + #### 日 + - return Number 获取日期。 + ```js -dayjs().date(); +dayjs().date() ``` + #### 星期 + - return Number 获取星期。 + ```js -dayjs().day(); +dayjs().day() ``` + #### 时 + - return Number 获取小时。 + ```js -dayjs().hour(); +dayjs().hour() ``` + #### 分 + - return Number 获取分钟。 + ```js -dayjs().minute(); +dayjs().minute() ``` + #### 秒 + - return Number 获取秒。 + ```js -dayjs().second(); +dayjs().second() ``` + #### 毫秒 + - return Number 获取毫秒。 + ```js -dayjs().millisecond(); +dayjs().millisecond() ``` + #### 设置 + 设置时间 传入的单位 (unit) 对大小写不敏感。 + ```js dayjs().set(unit : String, value : Int); dayjs().set('date', 1); @@ -192,47 +243,70 @@ dayjs().set('second', 30); | `millisecond` | `ms` | 毫秒 | --- + ### 操作 + 您可以对 `Dayjs` 对象如下增加减少之类的操作: + ```js -dayjs().startOf('month').add(1, 'day').subtract(1, 'year') +dayjs() + .startOf('month') + .add(1, 'day') + .subtract(1, 'year') ``` + #### 增加 + 增加时间并返回一个新的 `Dayjs()` 对象。 + ```js dayjs().add(value : Number, unit : String); dayjs().add(7, 'day'); ``` + #### 减少 + 减少时间并返回一个新的 `Dayjs()` 对象,使用方法和 `dayjs#add` 相同。 + ```js dayjs().subtract(value : Number, unit : String); dayjs().subtract(7, 'year'); ``` + #### 开头时间 + 返回当前时间的开头时间的 `Dayjs()` 对象,如月份的第一天。 + ```js dayjs().startOf(unit : String); dayjs().startOf('week'); // 取决于 locale 文件里 `weekStart` 的值 ``` + #### 末尾时间 + 返回当前时间的末尾时间的 `Dayjs()` 对象,如月份的最后一天。 + ```js dayjs().endOf(unit : String); dayjs().endOf('month'); ``` + --- + ### 显示 + 格式化 `Dayjs` 对象并展示。 + #### 格式化 + - return String 接收一系列的时间日期字符串并替换成相应的值。 ```js -dayjs().format(String); -dayjs().format(); // "2014-09-08T08:02:17-05:00" (ISO 8601, no fractional seconds) -dayjs().format("{YYYY} MM-DDTHH:mm:ssZ[Z]"); // "{2014} 09-08T08:02:17-05:00Z" +dayjs().format(String) +dayjs().format() // "2014-09-08T08:02:17-05:00" (ISO 8601, no fractional seconds) +dayjs().format('{YYYY} MM-DDTHH:mm:ssZ[Z]') // "{2014} 09-08T08:02:17-05:00Z" ``` 详情如下: @@ -248,14 +322,14 @@ dayjs().format("{YYYY} MM-DDTHH:mm:ssZ[Z]"); // "{2014} 09-08T08:02:17-05:00Z" | `D` | 1-31 | 月份里的一天 | | `DD` | 01-31 | 月份里的一天,两位数 | | `d` | 0-6 | 一周中的一天,星期天是 0 | -| `dd` | Su-Sa | 最简写的一周中一天的名称 | -| `ddd` | Sun-Sat | 简写的一周中一天的名称 | +| `dd` | Su-Sa | 最简写的一周中一天的名称 | +| `ddd` | Sun-Sat | 简写的一周中一天的名称 | | `dddd` | Sunday-Saturday | 一周中一天的名称 | | `H` | 0-23 | 小时 | | `HH` | 00-23 | 小时,两位数 | -| `m` | 0-59 | 分钟 | -| `mm` | 00-59 | 分钟,两位数 | -| `s` | 0-59 | 秒 | +| `m` | 0-59 | 分钟 | +| `mm` | 00-59 | 分钟,两位数 | +| `s` | 0-59 | 秒 | | `ss` | 00-59 | 秒 两位数 | | `SSS` | 000-999 | 秒 三位数 | | `Z` | +5:00 | UTC 的偏移量 | @@ -267,30 +341,38 @@ dayjs().format("{YYYY} MM-DDTHH:mm:ssZ[Z]"); // "{2014} 09-08T08:02:17-05:00Z" - 本地化的长日期格式 `L LT LTS ...` 可以使用插件 [`LocalizedFormat`](./Plugin.md#localizedFormat) #### 时间差 + - return Number 获取两个 `Dayjs` 对象的时间差,默认毫秒。 + ```js -const date1 = dayjs('2019-01-25'); -const date2 = dayjs('2018-06-05'); -date1.diff(date2); // 20214000000 -date1.diff(date2, 'month'); // 7 -date1.diff(date2, 'month', true); // 7.645161290322581 -date1.diff(date2, 'day'); // 233 +const date1 = dayjs('2019-01-25') +const date2 = dayjs('2018-06-05') +date1.diff(date2) // 20214000000 +date1.diff(date2, 'month') // 7 +date1.diff(date2, 'month', true) // 7.645161290322581 +date1.diff(date2, 'day') // 233 ``` + #### Unix 时间戳 (毫秒) + - return Number 返回 Unix 时间戳 (毫秒) + ```js -dayjs().valueOf(); +dayjs().valueOf() ``` + #### Unix 时间戳 (秒) + - return Number 返回 Unix 时间戳 (秒)。 + ```js -dayjs().unix(); +dayjs().unix() ``` ### UTC 偏移量 (分) @@ -298,81 +380,111 @@ dayjs().unix(); 返回 UTC 偏移量 (分) ```js -dayjs().utcOffset(); +dayjs().utcOffset() ``` #### 天数 (月) + - return Number 返回月份的天数。 + ```js -dayjs().daysInMonth(); +dayjs().daysInMonth() ``` + #### Date 对象 + - return Javascript `Date` object 返回原生的 `Date` 对象。 + ```js -dayjs().toDate(); +dayjs().toDate() ``` + #### 数组 + - return Array 返回包含时间数值的数组。 + ```js -dayjs().toArray(); //[2018, 8, 18, 00, 00, 00, 000]; +dayjs().toArray() //[2018, 8, 18, 00, 00, 00, 000]; ``` + #### As JSON + - return JSON String 当序列化 `Dayjs` 对象时,会返回 ISO8601 格式的字符串。 + ```js -dayjs().toJSON(); //"2018-08-08T00:00:00.000Z" +dayjs().toJSON() //"2018-08-08T00:00:00.000Z" ``` + #### ISO 8601 字符串 + - return String 返回 ISO8601 格式的字符串。 + ```js -dayjs().toISOString(); +dayjs().toISOString() ``` + #### 对象 + - return Object 返回包含时间数值的对象。 + ```js -dayjs().toObject();// { years:2018, months:8, date:18, hours:0, minutes:0, seconds:0, milliseconds:0} +dayjs().toObject() // { years:2018, months:8, date:18, hours:0, minutes:0, seconds:0, milliseconds:0} ``` + #### 字符串 + - return String ```js -dayjs().toString(); +dayjs().toString() ``` + --- + ### 查询 + #### 是否之前 + - return Boolean 检查一个 `Dayjs` 对象是否在另一个 `Dayjs` 对象时间之前。 + ```js dayjs().isBefore(Dayjs, unit? : String); dayjs().isBefore(dayjs()); // false dayjs().isBefore(dayjs(), 'year'); // false ``` + #### 是否相同 + - return Boolean 检查一个 `Dayjs` 对象是否和另一个 `Dayjs` 对象时间相同。 + ```js dayjs().isSame(Dayjs, unit? : String); dayjs().isSame(dayjs()); // true dayjs().isSame(dayjs(), 'year'); // true ``` + #### 是否之后 + - return Boolean 检查一个 `Dayjs` 对象是否在另一个 `Dayjs` 对象时间之后。 + ```js dayjs().isAfter(Dayjs, unit? : String); dayjs().isAfter(dayjs()); // false @@ -384,11 +496,11 @@ dayjs().isAfter(dayjs(), 'year'); // false 返回一个 `boolean` 验证传入值是否是一个 Dayjs 对象. ```js -dayjs.isDayjs(dayjs()); // true -dayjs.isDayjs(new Date()); // false +dayjs.isDayjs(dayjs()) // true +dayjs.isDayjs(new Date()) // false ``` -也可以使用 `instanceof` +也可以使用 `instanceof` ```js dayjs() instanceof dayjs // true diff --git a/docs/zh-cn/I18n.md b/docs/zh-cn/I18n.md index ecb99a58..8208bf81 100644 --- a/docs/zh-cn/I18n.md +++ b/docs/zh-cn/I18n.md @@ -16,7 +16,7 @@ Day.js 内置的是英语(English - United States)语言 #### 改变全局语言 -* 返回使用语言的字符串 +- 返回使用语言的字符串 ```js import 'dayjs/locale/zh-cn' @@ -28,23 +28,25 @@ dayjs.locale(customizedLocaleObject) // 使用自定义语言 dayjs.locale('en') // 全局使用默认的英语语言 ``` -* 改变全局语言并不会影响在此之前生成的实例 +- 改变全局语言并不会影响在此之前生成的实例 #### 改变当前实例的语言 -* 改变语言并返回新的`Dayjs` 对象 +- 改变语言并返回新的`Dayjs` 对象 用法与`dayjs#locale`一致, 但只影响当前实例的语言设置 ```js import 'dayjs/locale/es' -dayjs().locale('es').format() // 局部修改语言配置 +dayjs() + .locale('es') + .format() // 局部修改语言配置 dayjs('2018-4-28', { locale: 'es' }) // 在新建实例时指定 ``` ## 安装 -* 通过 NPM: +- 通过 NPM: ```javascript import 'dayjs/locale/es' // 按需加载 @@ -52,17 +54,22 @@ import 'dayjs/locale/es' // 按需加载 // import locale_es from 'dayjs/locale/es' -> 加载并获取 locale_es 配置对象 dayjs.locale('es') // 全局使用 -dayjs().locale('es').format() // 当前实例使用 +dayjs() + .locale('es') + .format() // 当前实例使用 ``` -* 通过 CDN: +- 通过 CDN: + ```html @@ -70,11 +77,12 @@ dayjs().locale('es').format() // 当前实例使用 ## 自定义 -你可以根据需要自由的编写一个Day.js语言配置 +你可以根据需要自由的编写一个 Day.js 语言配置 -同时欢迎提交PR与大家分享你的语言配置 +同时欢迎提交 PR 与大家分享你的语言配置 Day.js 的语言配置模版 + ```javascript const localeObject = { name: 'es', // 语言名 String @@ -85,7 +93,8 @@ const localeObject = { months: 'Enero_Febrero ... '.split('_'), // 月份 Array monthsShort: 'Jan_F'.split('_'), // 可选, 短的月份 Array, 如果没提供则使用前三个字符 ordinal: n => `${n}º`, // 序号生成工厂函数 Function (number) => return number + output - relativeTime: { // 相对时间, %s %d 不用翻译 + relativeTime: { + // 相对时间, %s %d 不用翻译 future: 'in %s', // e.g. in 2 hours, %s been replaced with 2hours past: '%s ago', s: 'a few seconds', @@ -104,6 +113,7 @@ const localeObject = { ``` Day.js 的语言配置本地加载样例 + ```javascript import dayjs from 'dayjs' @@ -112,4 +122,4 @@ const locale = { ... } // 你的 Day.js 语言配置 dayjs.locale(locale, null, true) // 设置配置 export default locale -``` \ No newline at end of file +``` diff --git a/docs/zh-cn/Installation.md b/docs/zh-cn/Installation.md index 8384c51c..46f4deeb 100644 --- a/docs/zh-cn/Installation.md +++ b/docs/zh-cn/Installation.md @@ -3,6 +3,7 @@ 可以有如下多种方法安装使用 Day.js: - NPM: + ```console npm install dayjs --save ``` @@ -11,17 +12,19 @@ npm install dayjs --save import dayjs from 'dayjs' // 或者 CommonJS // var dayjs = require('dayjs'); -dayjs().format(); +dayjs().format() ``` + - CDN: + ```html ``` - 下载到您自己的服务器上: -从 [https://unpkg.com/dayjs/](https://unpkg.com/dayjs/) 下载最新的 Dayjs 源文件,并自行部署到您的服务器上。 \ No newline at end of file +从 [https://unpkg.com/dayjs/](https://unpkg.com/dayjs/) 下载最新的 Dayjs 源文件,并自行部署到您的服务器上。 diff --git a/docs/zh-cn/Plugin.md b/docs/zh-cn/Plugin.md index b27b28a9..3ce2cd1c 100644 --- a/docs/zh-cn/Plugin.md +++ b/docs/zh-cn/Plugin.md @@ -10,7 +10,7 @@ #### Extend -* 将返回dayjs类 +- 将返回 dayjs 类 使用插件 @@ -22,7 +22,7 @@ dayjs.extend(plugin, options) // 带参数加载插件 ## 安装 -* 通过 NPM: +- 通过 NPM: ```javascript import dayjs from 'dayjs' @@ -31,20 +31,22 @@ import advancedFormat from 'dayjs/plugin/advancedFormat' // 按需加载 dayjs.extend(advancedFormat) // 使用插件 ``` -* 通过 CDN: +- 通过 CDN: + ```html ``` ## 官方插件列表 ### AdvancedFormat - - AdvancedFormat 扩展了 `dayjs().format` API 以支持更多模版 + +- AdvancedFormat 扩展了 `dayjs().format` API 以支持更多模版 ```javascript import AdvancedFormat from 'dayjs/plugin/advancedFormat' @@ -56,17 +58,18 @@ dayjs().format('Q Do k kk X x') 扩展的模版列表: -| 模版 | 输出 | 简介 | -| ------ | ---------------- | ------------------------------------- | -| `Q` | 1-4 | 季度 | -| `Do` | 1st 2nd ... 31st | 带序号的月份 | -| `k` | 1-23 | 时:由 1 开始 | -| `kk` | 01-23 | 时:由 1 开始,二位数 | -| `X` | 1360013296 | 秒为单位的Unix时间戳 | -| `x` | 1360013296123 | 毫秒单位的Unix时间戳 | +| 模版 | 输出 | 简介 | +| ---- | ---------------- | ---------------------- | +| `Q` | 1-4 | 季度 | +| `Do` | 1st 2nd ... 31st | 带序号的月份 | +| `k` | 1-23 | 时:由 1 开始 | +| `kk` | 01-23 | 时:由 1 开始,二位数 | +| `X` | 1360013296 | 秒为单位的 Unix 时间戳 | +| `x` | 1360013296123 | 毫秒单位的 Unix 时间戳 | ### LocalizedFormat - - LocalizedFormat 扩展了 `dayjs().format` API 以支持更多本地化的长日期格式. + +- LocalizedFormat 扩展了 `dayjs().format` API 以支持更多本地化的长日期格式. ```javascript import LocalizedFormat from 'dayjs/plugin/localizedFormat' @@ -78,7 +81,7 @@ dayjs().format('L LT') 扩展的模版列表: -| 模版 | 格式 | 输出 | +| 模版 | 格式 | 输出 | | ------ | ------------------------- | --------------------------------- | | `LT` | h:mm A | 8:02 PM | | `LTS` | h:mm:ss A | 8:02:18 PM | @@ -88,7 +91,8 @@ dayjs().format('L LT') | `LLLL` | dddd, MMMM D, YYYY h:mm A | Thursday, August 16, 2018 8:02 PM | ### RelativeTime - - RelativeTime 增加了 `.from` `.to` `.fromNow` `.toNow` 4个 API 来展示相对的时间 (e.g. 3 小时以前). + +- RelativeTime 增加了 `.from` `.to` `.fromNow` `.toNow` 4 个 API 来展示相对的时间 (e.g. 3 小时以前). ```javascript import relativeTime from 'dayjs/plugin/relativeTime' @@ -109,7 +113,7 @@ dayjs().toNow() 返回 `string` 距离现在的相对时间 -#### 距离 X 的相对时间 `.from(compared: Dayjs, withoutSuffix?: boolean)` +#### 距离 X 的相对时间 `.from(compared: Dayjs, withoutSuffix?: boolean)` 返回 `string` 距离 X 的相对时间 @@ -117,39 +121,41 @@ dayjs().toNow() 返回 `string` 到现在的相对时间 -#### 到 X 的相对时间 `.to(compared: Dayjs, withoutSuffix?: boolean)` +#### 到 X 的相对时间 `.to(compared: Dayjs, withoutSuffix?: boolean)` 返回 `string` 到 X 的相对时间 -| Range | Key | Sample Output | -| ------------------------ | ---- | -------------------------------- | -| 0 到 44 秒 | s | 几秒前 | -| 45 到 89 秒 | m | 1 分钟前 | -| 90 秒 到 44 分 | mm | 2 分钟前 ... 44 分钟前 | -| 45 到 89 分 | h | 1 小时前 | -| 90 分 到 21 小时 | hh | 2 小时前 ... 21 小时前 | -| 22 到 35 小时 | d | 1 天前 | -| 36 小时 到 25 天 | dd | 2 天前 ... 25 天前 | -| 26 到 45 天 | M | 1 个月前 | -| 46 天 到 10 月 | MM | 2 个月前 ... 10 个月前 | -| 11 月 到 17月 | y | 1 年前 | -| 18 月以上 | yy | 2 年前 ... 20 年前 | +| Range | Key | Sample Output | +| ---------------- | --- | ---------------------- | +| 0 到 44 秒 | s | 几秒前 | +| 45 到 89 秒 | m | 1 分钟前 | +| 90 秒 到 44 分 | mm | 2 分钟前 ... 44 分钟前 | +| 45 到 89 分 | h | 1 小时前 | +| 90 分 到 21 小时 | hh | 2 小时前 ... 21 小时前 | +| 22 到 35 小时 | d | 1 天前 | +| 36 小时 到 25 天 | dd | 2 天前 ... 25 天前 | +| 26 到 45 天 | M | 1 个月前 | +| 46 天 到 10 月 | MM | 2 个月前 ... 10 个月前 | +| 11 月 到 17 月 | y | 1 年前 | +| 18 月以上 | yy | 2 年前 ... 20 年前 | ## IsLeapYear - - IsLeapYear 增加了 `.isLeapYear` API 返回一个 `boolean` 来展示一个 `Dayjs`'s 的年份是不是闰年. + +- IsLeapYear 增加了 `.isLeapYear` API 返回一个 `boolean` 来展示一个 `Dayjs`'s 的年份是不是闰年. ```javascript import isLeapYear from 'dayjs/plugin/isLeapYear' dayjs.extend(isLeapYear) -dayjs('2000-01-01').isLeapYear(); // true +dayjs('2000-01-01').isLeapYear() // true ``` ### BuddhistEra + - BuddhistEra 扩展了 `dayjs().format` API 以支持佛历格式化. - 佛历是一个年份编号系统,主要用于柬埔寨、老挝、缅甸和泰国等东南亚国家以及斯里兰卡、马来西亚和新加坡的中国人,用于宗教或官方场合([Wikipedia](https://en.wikipedia.org/wiki/Buddhist_calendar)) -- 要计算BE年,只需在年份中添加543。 例如,1977年5月26日AD / CE应显示为2520年5月26日BE(1977 + 543) +- 要计算 BE 年,只需在年份中添加 543。 例如,1977 年 5 月 26 日 AD / CE 应显示为 2520 年 5 月 26 日 BE(1977 + 543) ```javascript import buddhistEra from 'dayjs/plugin/buddhistEra' @@ -161,43 +167,46 @@ dayjs().format('BBBB BB') List of added formats: -| Format | Output | Description | -| ------ | ---------------- | ------------------------------------- | -| `BBBB` | 2561 | Full BE Year (Year + 543) | -| `BB` | 61 | 2-digit of BE Year | +| Format | Output | Description | +| ------ | ------ | ------------------------- | +| `BBBB` | 2561 | Full BE Year (Year + 543) | +| `BB` | 61 | 2-digit of BE Year | ### IsSameOrAfter - - IsSameOrAfter 增加了 `.isSameOrAfter()` API 返回一个 `boolean` 来展示一个时间是否和一个时间相同或在一个时间之后. + +- IsSameOrAfter 增加了 `.isSameOrAfter()` API 返回一个 `boolean` 来展示一个时间是否和一个时间相同或在一个时间之后. ```javascript import isSameOrAfter from 'dayjs/plugin/isSameOrAfter' dayjs.extend(isSameOrAfter) -dayjs('2010-10-20').isSameOrAfter('2010-10-19', 'year'); +dayjs('2010-10-20').isSameOrAfter('2010-10-19', 'year') ``` ### IsSameOrBefore - - IsSameOrBefore 增加了 `.isSameOrBefore()` API 返回一个 `boolean` 来展示一个时间是否和一个时间相同或在一个时间之前. + +- IsSameOrBefore 增加了 `.isSameOrBefore()` API 返回一个 `boolean` 来展示一个时间是否和一个时间相同或在一个时间之前. ```javascript import isSameOrBefore from 'dayjs/plugin/isSameOrBefore' dayjs.extend(isSameOrBefore) -dayjs('2010-10-20').isSameOrBefore('2010-10-19', 'year'); +dayjs('2010-10-20').isSameOrBefore('2010-10-19', 'year') ``` ### IsBetween - - IsBetween 增加了 `.isBetween()` API 返回一个 `boolean` 来展示一个时间是否介于两个时间之间. + +- IsBetween 增加了 `.isBetween()` API 返回一个 `boolean` 来展示一个时间是否介于两个时间之间. ```javascript import isBetween from 'dayjs/plugin/isBetween' dayjs.extend(isBetween) -dayjs('2010-10-20').isBetween('2010-10-19', dayjs('2010-10-25'), 'year'); -dayjs('2016-10-30').isBetween('2016-01-01', '2016-10-30', null, '[)'); +dayjs('2010-10-20').isBetween('2010-10-19', dayjs('2010-10-25'), 'year') +dayjs('2016-10-30').isBetween('2016-01-01', '2016-10-30', null, '[)') // '[' 包含, '(' 不包含 ``` @@ -206,16 +215,17 @@ dayjs('2016-10-30').isBetween('2016-01-01', '2016-10-30', null, '[)'); - DayOfYear 增加了 `.dayOfYear()` API 返回一个 `number` 来表示 `Dayjs` 的日期是年中第几天,或设置成是年中第几天。 ```javascript -import dayOfYear from "dayjs/plugin/dayOfYear"; +import dayOfYear from 'dayjs/plugin/dayOfYear' -dayjs.extend(dayOfYear); +dayjs.extend(dayOfYear) -dayjs("2010-01-01").dayOfYear(); // 1 -dayjs("2010-01-01").dayOfYear(365); // 2010-12-31 +dayjs('2010-01-01').dayOfYear() // 1 +dayjs('2010-01-01').dayOfYear(365) // 2010-12-31 ``` ### WeekOfYear - - WeekOfYear 增加了 `.week()` API 返回一个 `number` 来表示 `Dayjs` 的日期是年中第几周. + +- WeekOfYear 增加了 `.week()` API 返回一个 `number` 来表示 `Dayjs` 的日期是年中第几周. ```javascript import weekOfYear from 'dayjs/plugin/weekOfYear' @@ -226,6 +236,7 @@ dayjs('06/27/2018').week() // 26 ``` ### QuarterOfYear + - QuarterOfYear 增加了 `.quarter()` API `number` 来表示 `Dayjs` 的日期是第几个季度. ```javascript @@ -233,11 +244,12 @@ import quarterOfYear from 'dayjs/plugin/quarterOfYear' dayjs.extend(quarterOfYear) -dayjs('2010-04-01').quarter(); // 2 +dayjs('2010-04-01').quarter() // 2 ``` ### CustomParseFormat - - CustomParseFormat 拓展了 `dayjs()` 支持自定义时间格式. + +- CustomParseFormat 拓展了 `dayjs()` 支持自定义时间格式. 使用方括号来表示需要保留的字符 (e.g. `[G]`) . @@ -252,54 +264,55 @@ dayjs('05/02/69 1:02:03 PM -05:00', 'MM/DD/YY H:mm:ss A Z') #### List of all available format tokens -| Format | Output | Description | -| ------ | ---------------- | --------------------------------- | -| `YY` | 18 | Two-digit year | -| `YYYY` | 2018 | Four-digit year | -| `M` | 1-12 | Month, beginning at 1 | -| `MM` | 01-12 | Month, 2-digits | -| `D` | 1-31 | Day of month | -| `DD` | 01-31 | Day of month, 2-digits | -| `H` | 0-23 | Hours | -| `HH` | 00-23 | Hours, 2-digits | -| `h` | 1-12 | Hours, 12-hour clock | -| `hh` | 01-12 | Hours, 12-hour clock, 2-digits | -| `m` | 0-59 | Minutes | -| `mm` | 00-59 | Minutes, 2-digits | -| `s` | 0-59 | Seconds | -| `ss` | 00-59 | Seconds, 2-digits | -| `S` | 0-9 | Hundreds of milliseconds, 1-digit | -| `SS` | 00-99 | Tens of milliseconds, 2-digits | -| `SSS` | 000-999 | Milliseconds, 3-digits | -| `Z` | -5:00 | Offset from UTC | -| `ZZ` | -0500 | Compact offset from UTC, 2-digits | -| `A` | AM PM | Post or ante meridiem, upper-case | -| `a` | am pm | Post or ante meridiem, lower-case | +| Format | Output | Description | +| ------ | ------- | --------------------------------- | +| `YY` | 18 | Two-digit year | +| `YYYY` | 2018 | Four-digit year | +| `M` | 1-12 | Month, beginning at 1 | +| `MM` | 01-12 | Month, 2-digits | +| `D` | 1-31 | Day of month | +| `DD` | 01-31 | Day of month, 2-digits | +| `H` | 0-23 | Hours | +| `HH` | 00-23 | Hours, 2-digits | +| `h` | 1-12 | Hours, 12-hour clock | +| `hh` | 01-12 | Hours, 12-hour clock, 2-digits | +| `m` | 0-59 | Minutes | +| `mm` | 00-59 | Minutes, 2-digits | +| `s` | 0-59 | Seconds | +| `ss` | 00-59 | Seconds, 2-digits | +| `S` | 0-9 | Hundreds of milliseconds, 1-digit | +| `SS` | 00-99 | Tens of milliseconds, 2-digits | +| `SSS` | 000-999 | Milliseconds, 3-digits | +| `Z` | -5:00 | Offset from UTC | +| `ZZ` | -0500 | Compact offset from UTC, 2-digits | +| `A` | AM PM | Post or ante meridiem, upper-case | +| `a` | am pm | Post or ante meridiem, lower-case | ## 自定义 -你可以根据需要自由的编写一个Day.js插件 +你可以根据需要自由的编写一个 Day.js 插件 + +欢迎提交 PR 与大家分享你的插件 -欢迎提交PR与大家分享你的插件 +Day.js 插件模版 -Day.js插件模版 ```javascript export default (option, dayjsClass, dayjsFactory) => { // 扩展 dayjs() 实例 // 例:添加 dayjs().isSameOrBefore() 实例方法 - dayjsClass.prototype.isSameOrBefore = function (arguments) {} + dayjsClass.prototype.isSameOrBefore = function(arguments) {} // 扩展 dayjs 类 // 例:添加 dayjs.utc() 类方法 - dayjsFactory.utc = (arguments) => {} + dayjsFactory.utc = arguments => {} // 覆盖已存在的 API // 例:扩展 dayjs().format() 方法 const oldFormat = dayjsClass.prototype.format - dayjsClass.prototype.format = function (arguments) { + dayjsClass.prototype.format = function(arguments) { // 原始format结果 const result = oldFormat(arguments) // 返回修改后结果 } } -``` \ No newline at end of file +``` diff --git a/docs/zh-cn/README.zh-CN.md b/docs/zh-cn/README.zh-CN.md index b110642d..82c488c1 100644 --- a/docs/zh-cn/README.zh-CN.md +++ b/docs/zh-cn/README.zh-CN.md @@ -24,15 +24,20 @@ > Day.js 是一个轻量的处理时间和日期的 JavaScript 库,和 Moment.js 的 API 设计保持完全一样. 如果您曾经用过 Moment.js, 那么您已经知道如何使用 Day.js ```js -dayjs().startOf('month').add(1, 'day').set('year', 2018).format('YYYY-MM-DD HH:mm:ss'); +dayjs() + .startOf('month') + .add(1, 'day') + .set('year', 2018) + .format('YYYY-MM-DD HH:mm:ss') ``` -* 🕒 和 Moment.js 相同的 API 和用法 -* 💪 不可变数据 (Immutable) -* 🔥 支持链式操作 (Chainable) -* 🌐 国际化 I18n -* 📦 仅 2kb 大小的微型库 -* 👫 全浏览器兼容 +- 🕒 和 Moment.js 相同的 API 和用法 +- 💪 不可变数据 (Immutable) +- 🔥 支持链式操作 (Chainable) +- 🌐 国际化 I18n +- 📦 仅 2kb 大小的微型库 +- 👫 全浏览器兼容 + --- ## 快速开始 @@ -54,7 +59,9 @@ dayjs('2018-08-08') // 解析 dayjs().format('{YYYY} MM-DDTHH:mm:ss SSS [Z] A') // 展示 -dayjs().set('month', 3).month() // 获取 +dayjs() + .set('month', 3) + .month() // 获取 dayjs().add(1, 'year') // 处理 @@ -74,8 +81,11 @@ import 'dayjs/locale/es' // 按需加载 dayjs.locale('es') // 全局使用西班牙语 -dayjs('2018-05-05').locale('zh-cn').format() // 在这个实例上使用简体中文 +dayjs('2018-05-05') + .locale('zh-cn') + .format() // 在这个实例上使用简体中文 ``` + 📚[国际化 I18n](./I18n.md) ### 插件 @@ -89,6 +99,7 @@ dayjs.extend(advancedFormat) // 使用插件 dayjs().format('Q Do k kk X x') // 使用扩展后的API ``` + 📚[插件列表](./Plugin.md) ## 开源协议 From dca0c9b3af7d2c4e207aeefd48b2a15d9f26737b Mon Sep 17 00:00:00 2001 From: Majid Madadi Date: Thu, 14 Feb 2019 17:59:04 +0330 Subject: [PATCH 02/25] fix: Word orders corrections for locale 'fa' (#491) --- src/locale/fa.js | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/src/locale/fa.js b/src/locale/fa.js index e7b64ea4..09d1d084 100644 --- a/src/locale/fa.js +++ b/src/locale/fa.js @@ -14,19 +14,19 @@ const locale = { LLLL: 'dddd, D MMMM YYYY HH:mm' }, relativeTime: { - future: '%s در', - past: 'پیش %s', + future: 'در %s', + past: '%s پیش', s: 'چند ثانیه', m: 'یک دقیقه', - mm: 'دقیقه %d', + mm: '%d دقیقه', h: 'یک ساعت', - hh: 'ساعت %d', + hh: '%d ساعت', d: 'یک روز', - dd: 'روز %d', + dd: '%d روز', M: 'یک ماه', - MM: 'ماه %d', + MM: '%d ماه', y: 'یک سال', - yy: 'سال %d' + yy: '%d سال' } } From 7653a55c5c21a987d7d0f34fa7f8ac667d62edfd Mon Sep 17 00:00:00 2001 From: Hui Hui <0w0@loli.pet> Date: Mon, 18 Feb 2019 14:05:44 +0800 Subject: [PATCH 03/25] fix: Update declaration file .diff .isBefore .isSame .isAfter (#496) --- index.d.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/index.d.ts b/index.d.ts index 3bc0cbc6..236a7d27 100644 --- a/index.d.ts +++ b/index.d.ts @@ -57,7 +57,7 @@ declare namespace dayjs { format(template?: string): string - diff(dayjs: Dayjs, unit: OpUnitType, float?: boolean): number + diff(dayjs: ConfigType, unit: OpUnitType, float?: boolean): number valueOf(): number @@ -77,11 +77,11 @@ declare namespace dayjs { toString(): string - isBefore(dayjs: Dayjs, unit?: OpUnitType): boolean + isBefore(dayjs: ConfigType, unit?: OpUnitType): boolean - isSame(dayjs: Dayjs, unit?: OpUnitType): boolean + isSame(dayjs: ConfigType, unit?: OpUnitType): boolean - isAfter(dayjs: Dayjs, unit?: OpUnitType): boolean + isAfter(dayjs: ConfigType, unit?: OpUnitType): boolean isLeapYear(): boolean From 4ad1830a0e0d4d2e2fe00a8ec6fee31e71521a8d Mon Sep 17 00:00:00 2001 From: Horst Schneider Date: Mon, 18 Feb 2019 12:24:36 +0100 Subject: [PATCH 04/25] chore: Refactor parseDate (#487) --- src/index.js | 22 +++++++++------------- test/parse.test.js | 36 +++++++++++++++++++++++++++++++++++- 2 files changed, 44 insertions(+), 14 deletions(-) diff --git a/src/index.js b/src/index.js index 96cda316..2e2cdbdb 100644 --- a/src/index.js +++ b/src/index.js @@ -46,21 +46,17 @@ Utils.isDayjs = isDayjs Utils.wrapper = wrapper const parseDate = (date) => { - let reg - if (date === null) return new Date(NaN) // Treat null as an invalid date - if (Utils.isUndefined(date)) return new Date() + if (date === null) return new Date(NaN) // null is invalid + if (Utils.isUndefined(date)) return new Date() // today if (date instanceof Date) return date - // eslint-disable-next-line no-cond-assign - if ((typeof date === 'string') - && (/.*[^Z]$/i.test(date)) // looking for a better way - && (reg = date.match(C.REGEX_PARSE))) { - // 2018-08-08 or 20180808 - return new Date( - reg[1], reg[2] - 1, reg[3] || 1, - reg[4] || 0, reg[5] || 0, reg[6] || 0, reg[7] || 0 - ) + if (typeof date === 'string' && !/Z$/i.test(date)) { + const d = date.match(C.REGEX_PARSE) + if (d) { + return new Date(d[1], d[2] - 1, d[3] || 1, d[4] || 0, d[5] || 0, d[6] || 0, d[7] || 0) + } } - return new Date(date) // timestamp + + return new Date(date) // everything else } class Dayjs { diff --git a/test/parse.test.js b/test/parse.test.js index 1204a0f9..e84a2441 100644 --- a/test/parse.test.js +++ b/test/parse.test.js @@ -15,7 +15,7 @@ describe('Parse', () => { expect(dayjs().valueOf()).toBe(moment().valueOf()) }) - it('String 20130208', () => { + it('moment-js like formatted dates', () => { global.console.warn = jest.genMockFunction()// moment.js '2018-4-1 1:1:1:22' will throw warn let d = '20130108' expect(dayjs(d).valueOf()).toBe(moment(d).valueOf()) @@ -46,6 +46,40 @@ describe('Parse', () => { expect(dayjs(time).valueOf()).toBe(moment(time).valueOf()) }) + it('String RFC 2822, time and zone', () => { + const time = 'Mon, 11 Feb 2019 09:46:50 GMT+1' + const expected = '2019-02-11T08:46:50.000Z' + const d = dayjs(time) + expect(d.toISOString()).toEqual(expected) + expect(d.valueOf()).toBe(moment(time).valueOf()) + }) + + it('String ECMAScript, time and zone', () => { + // should parse dates formatted in ECMA script format + // see https://www.ecma-international.org/ecma-262/9.0/index.html#sec-date.prototype.tostring + const time = 'Mon Feb 11 2019 11:01:37 GMT+0100 (Mitteleuropäische Normalzeit)' + const expected = '2019-02-11T10:01:37.000Z' + const d = dayjs(time) + expect(d.toISOString()).toEqual(expected) + expect(d.valueOf()).toBe(moment(time).valueOf()) + }) + + it('rejects invalid values', () => { + expect(dayjs({}).isValid()).toBe(false) + expect(dayjs(() => '2018-01-01').isValid()).toBe(false) + expect(dayjs(Infinity).isValid()).toBe(false) + expect(dayjs(NaN).isValid()).toBe(false) + expect(dayjs([2018, 5, 1, 13, 52, 44]).isValid()).toBe(false) // Arrays with time part + }) + + it('parses Arrays with date part', () => { + const dateParts = [2018, 5, 1] + const expected = '2018-05-01T00:00:00.000Z' + const d = dayjs(dateParts) + const normalized = d.add(d.utcOffset(), 'minutes') // make test run in every timezone + expect(normalized.toISOString()).toEqual(expected) + }) + it('String Other, Null and isValid', () => { global.console.warn = jest.genMockFunction()// moment.js otherString will throw warn expect(dayjs('otherString').toString().toLowerCase()).toBe(moment('otherString').toString().toLowerCase()) From 50971bca798b8ead16a6a983ba1ff7ce5864c7f0 Mon Sep 17 00:00:00 2001 From: Denis Sokolov Date: Tue, 19 Feb 2019 12:27:28 +0200 Subject: [PATCH 05/25] docs: Fix doc error in format escaping with curly brackets (#502) --- docs/en/API-reference.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/en/API-reference.md b/docs/en/API-reference.md index b4e8986c..bd3a7fdc 100644 --- a/docs/en/API-reference.md +++ b/docs/en/API-reference.md @@ -257,12 +257,12 @@ dayjs().endOf('month') ### Format `.format(stringWithTokens: string)` Returns a `string` with the `Dayjs`'s formatted date. -To escape characters, wrap them in square or curly brackets (e.g. `[G] {um}`). +To escape characters, wrap them in square brackets (e.g. `[G] [um]`). ```js dayjs().format() // current date in ISO6801, without fraction seconds e.g. '2020-04-02T08:02:17-05:00' -dayjs('2019-01-25').format('{YYYY} MM-DDTHH:mm:ssZ[Z]') // '{2019} 01-25T00:00:00-02:00Z' +dayjs('2019-01-25').format('[YYYY] YYYY-MM-DDTHH:mm:ssZ[Z]') // 'YYYY 2019-01-25T00:00:00-02:00Z' dayjs('2019-01-25').format('DD/MM/YYYY') // '25/01/2019' ``` From ac24264a88968f48dcab2ea9389046a15b201816 Mon Sep 17 00:00:00 2001 From: splashwizard Date: Tue, 19 Feb 2019 19:57:59 +0800 Subject: [PATCH 06/25] docs: Fix doc format escape error --- docs/en/API-reference.md | 2 +- docs/es-es/API-reference.md | 4 ++-- docs/ja/API-reference.md | 2 +- docs/ko/API-reference.md | 4 ++-- docs/pt-br/API-reference.md | 4 ++-- docs/zh-cn/API-reference.md | 2 +- 6 files changed, 9 insertions(+), 9 deletions(-) diff --git a/docs/en/API-reference.md b/docs/en/API-reference.md index bd3a7fdc..13af4d78 100644 --- a/docs/en/API-reference.md +++ b/docs/en/API-reference.md @@ -257,7 +257,7 @@ dayjs().endOf('month') ### Format `.format(stringWithTokens: string)` Returns a `string` with the `Dayjs`'s formatted date. -To escape characters, wrap them in square brackets (e.g. `[G] [um]`). +To escape characters, wrap them in square brackets (e.g. `[A] [MM]`). ```js dayjs().format() // current date in ISO6801, without fraction seconds e.g. '2020-04-02T08:02:17-05:00' diff --git a/docs/es-es/API-reference.md b/docs/es-es/API-reference.md index ae46d814..b173ea51 100644 --- a/docs/es-es/API-reference.md +++ b/docs/es-es/API-reference.md @@ -257,12 +257,12 @@ dayjs().endOf('month') ### Dar formato `.format(stringWithTokens: string)` Devuelve un dato de tipo `string` con la fecha del objeto `Dayjs` formateada. -Para escapar caracteres, estos se han de encerrar entre corchetes o llaves (p.ej.: `[G] {um}`). +Para escapar caracteres, estos se han de encerrar entre corchetes (p.ej.: `[A] [MM]`). ```js dayjs().format() // fecha actual en ISO6801, sin fracciones de segundo p.ej. '2020-04-02T08:02:17-05:00' -dayjs('2019-01-25').format('{YYYY} MM-DDTHH:mm:ssZ[Z]') // '{2019} 01-25T00:00:00-02:00Z' +dayjs('2019-01-25').format('[YYYY] YYYY-MM-DDTHH:mm:ssZ[Z]') // 'YYYY 2019-01-25T00:00:00-02:00Z' dayjs('2019-01-25').format('DD/MM/YYYY') // '25/01/2019' ``` diff --git a/docs/ja/API-reference.md b/docs/ja/API-reference.md index bad37952..22a854d1 100644 --- a/docs/ja/API-reference.md +++ b/docs/ja/API-reference.md @@ -306,7 +306,7 @@ dayjs().endOf('month') ```js dayjs().format(String) dayjs().format() // "2014-09-08T08:02:17-05:00" (ISO 8601 形式、小数部は含まない) -dayjs().format('{YYYY} MM-DDTHH:mm:ssZ[Z]') // "{2014} 09-08T08:02:17-05:00Z" +dayjs('2019-01-25').format('[YYYY] YYYY-MM-DDTHH:mm:ssZ[Z]') // 'YYYY 2019-01-25T00:00:00-02:00Z' ``` - 文字列内の文字をエスケープするには、文字を角括弧で囲みます (例: [Z]) 。 diff --git a/docs/ko/API-reference.md b/docs/ko/API-reference.md index 073c1535..08775382 100644 --- a/docs/ko/API-reference.md +++ b/docs/ko/API-reference.md @@ -256,12 +256,12 @@ dayjs().endOf('month') ### Format `.format(stringWithTokens: string)` `Dayjs` 오브젝트 시간을 기본 형식으로 출력합니다. 반환 형식은 `string` 입니다. -예외하고 싶은 문자일 경우, 대괄호나 중괄호를 사용하여 묶으면됩니다. (예, `[G] {um}`) +예외하고 싶은 문자일 경우, 대괄호나 중괄호를 사용하여 묶으면됩니다. (예, `[A] [MM]`) ```js dayjs().format() // 분과 초가 없는 ISO5801 형식의 현재 시간을 나타냅니다. 예: '2020-04-02T08:02:17-05:00' -dayjs('2019-01-25').format('{YYYY} MM-DDTHH:mm:ssZ[Z]') // '{2019} 01-25T00:00:00-02:00Z' +dayjs('2019-01-25').format('[YYYY] YYYY-MM-DDTHH:mm:ssZ[Z]') // 'YYYY 2019-01-25T00:00:00-02:00Z' dayjs('2019-01-25').format('DD/MM/YYYY') // '25/01/2019' ``` diff --git a/docs/pt-br/API-reference.md b/docs/pt-br/API-reference.md index 9c4715ca..ff7bd7fc 100644 --- a/docs/pt-br/API-reference.md +++ b/docs/pt-br/API-reference.md @@ -255,12 +255,12 @@ dayjs().endOf('month') ### Formatação `.format(stringWithTokens: string)` Retorna uma `string` com um objeto `Dayjs` contendo a data formatada. -Para escapar caracteres, envolva-os entre colchetes ou chaves (por exemplo: `[G] {um}`). +Para escapar caracteres, envolva-os entre colchetes (por exemplo: `[A] [MM]`). ```js dayjs().format() // current date in ISO6801, without fraction seconds e.g. '2020-04-02T08:02:17-05:00' -dayjs('2019-01-25').format('{YYYY} MM-DDTHH:mm:ssZ[Z]') // '{2019} 01-25T00:00:00-02:00Z' +dayjs('2019-01-25').format('[YYYY] YYYY-MM-DDTHH:mm:ssZ[Z]') // 'YYYY 2019-01-25T00:00:00-02:00Z' dayjs('2019-01-25').format('DD/MM/YYYY') // '25/01/2019' ``` diff --git a/docs/zh-cn/API-reference.md b/docs/zh-cn/API-reference.md index 76e14c3c..faa20a00 100644 --- a/docs/zh-cn/API-reference.md +++ b/docs/zh-cn/API-reference.md @@ -305,7 +305,7 @@ dayjs().endOf('month'); ```js dayjs().format(String) -dayjs().format() // "2014-09-08T08:02:17-05:00" (ISO 8601, no fractional seconds) +dayjs('2019-01-25').format('[YYYY] YYYY-MM-DDTHH:mm:ssZ[Z]') // 'YYYY 2019-01-25T00:00:00-02:00Z' dayjs().format('{YYYY} MM-DDTHH:mm:ssZ[Z]') // "{2014} 09-08T08:02:17-05:00Z" ``` From af2b9f4d2b604216a15c1c5aa76be5c64213edc8 Mon Sep 17 00:00:00 2001 From: Wagner Souza Date: Wed, 20 Feb 2019 23:42:36 -0300 Subject: [PATCH 07/25] docs: Fix typo README-pt-br.md (#503) --- docs/pt-br/README-pt-br.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/pt-br/README-pt-br.md b/docs/pt-br/README-pt-br.md index 06fd9726..1b18e891 100644 --- a/docs/pt-br/README-pt-br.md +++ b/docs/pt-br/README-pt-br.md @@ -102,7 +102,7 @@ dayjs().format('Q Do k kk X x') // mais formatos disponíveis pelo plugin 📚[Lista de Plugins](./Plugin.md) -## Patricionadores +## Patrocinadores Ajude este projeto se tornando um patrocinador. O seu logo será exibido aqui, com um link para o seu site. [[Tornar-se um Patrocinador](https://opencollective.com/dayjs#sponsor)]. From ed7fd3ffa8c43aed1e9a9d78b414be0cf4c3903a Mon Sep 17 00:00:00 2001 From: splashwizard Date: Thu, 21 Feb 2019 10:52:55 +0800 Subject: [PATCH 08/25] chore: Update issue templates --- .github/ISSUE_TEMPLATE/--bug-report.md | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 .github/ISSUE_TEMPLATE/--bug-report.md diff --git a/.github/ISSUE_TEMPLATE/--bug-report.md b/.github/ISSUE_TEMPLATE/--bug-report.md new file mode 100644 index 00000000..1c098f11 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/--bug-report.md @@ -0,0 +1,17 @@ +--- +name: "\U0001F4A9Bug report" +about: Create a report to help us improve +title: '' +labels: '' +assignees: '' + +--- + +### Day.js version + + + +### OS/Browsers version + + +### Steps to reproduce From a01433e363bb8dd1fe84402828535a1ed9236ee5 Mon Sep 17 00:00:00 2001 From: splashwizard Date: Thu, 21 Feb 2019 11:06:20 +0800 Subject: [PATCH 09/25] chore: update bug-report.md --- .github/ISSUE_TEMPLATE/--bug-report.md | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/.github/ISSUE_TEMPLATE/--bug-report.md b/.github/ISSUE_TEMPLATE/--bug-report.md index 1c098f11..1ff3f734 100644 --- a/.github/ISSUE_TEMPLATE/--bug-report.md +++ b/.github/ISSUE_TEMPLATE/--bug-report.md @@ -7,11 +7,13 @@ assignees: '' --- -### Day.js version +**Describe the bug** +A clear and concise description of what the bug is. +**Expected behavior** +A clear and concise description of what you expected to happen. - -### OS/Browsers version - - -### Steps to reproduce +**Information** + - Day.js Version [e.g. v1.0.0] + - OS: [e.g. iOS] + - Browser [e.g. chrome 62] From 55ae8c46544d4e533a94d4bfcfc1d443505d60e0 Mon Sep 17 00:00:00 2001 From: Yuya Tanaka Date: Sat, 23 Feb 2019 23:49:01 +0900 Subject: [PATCH 10/25] fix: Add plugin type definitions (#418) --- .gitignore | 1 + .npmignore | 3 ++- build/index.js | 3 +++ package.json | 5 +++-- test/index.d.test.ts | 18 ++++++++++++++--- test/plugin/dayOfYear.d.test.ts | 6 ++++++ test/plugin/isBetween.d.test.ts | 6 ++++++ test/plugin/isLeapYear.d.test.ts | 6 ++++++ test/plugin/isSameOrAfter.d.test.ts | 6 ++++++ test/plugin/isSameOrBefore.d.test.ts | 6 ++++++ test/plugin/quarterOfYear.d.test.ts | 6 ++++++ test/plugin/relativeTime.d.test.ts | 20 +++++++++++++++++++ test/plugin/weekOfYear.d.test.ts | 6 ++++++ tsconfig.json | 20 +++++++++++++++++++ index.d.ts => types/index.d.ts | 29 +++++++++++++++------------- types/plugin/advancedFormat.d.ts | 4 ++++ types/plugin/buddhistEra.d.ts | 4 ++++ types/plugin/customParseFormat.ts | 4 ++++ types/plugin/dayOfYear.d.ts | 10 ++++++++++ types/plugin/isBetween.d.ts | 10 ++++++++++ types/plugin/isLeapYear.d.ts | 10 ++++++++++ types/plugin/isSameOrAfter.d.ts | 10 ++++++++++ types/plugin/isSameOrBefore.d.ts | 10 ++++++++++ types/plugin/localizedFormat.d.ts | 4 ++++ types/plugin/quarterOfYear.d.ts | 10 ++++++++++ types/plugin/relativeTime.d.ts | 13 +++++++++++++ types/plugin/weekOfYear.d.ts | 10 ++++++++++ 27 files changed, 221 insertions(+), 19 deletions(-) create mode 100644 test/plugin/dayOfYear.d.test.ts create mode 100644 test/plugin/isBetween.d.test.ts create mode 100644 test/plugin/isLeapYear.d.test.ts create mode 100644 test/plugin/isSameOrAfter.d.test.ts create mode 100644 test/plugin/isSameOrBefore.d.test.ts create mode 100644 test/plugin/quarterOfYear.d.test.ts create mode 100644 test/plugin/relativeTime.d.test.ts create mode 100644 test/plugin/weekOfYear.d.test.ts create mode 100644 tsconfig.json rename index.d.ts => types/index.d.ts (58%) create mode 100644 types/plugin/advancedFormat.d.ts create mode 100644 types/plugin/buddhistEra.d.ts create mode 100644 types/plugin/customParseFormat.ts create mode 100644 types/plugin/dayOfYear.d.ts create mode 100644 types/plugin/isBetween.d.ts create mode 100644 types/plugin/isLeapYear.d.ts create mode 100644 types/plugin/isSameOrAfter.d.ts create mode 100644 types/plugin/isSameOrBefore.d.ts create mode 100644 types/plugin/localizedFormat.d.ts create mode 100644 types/plugin/quarterOfYear.d.ts create mode 100644 types/plugin/relativeTime.d.ts create mode 100644 types/plugin/weekOfYear.d.ts diff --git a/.gitignore b/.gitignore index c90d1cc7..d022dbed 100644 --- a/.gitignore +++ b/.gitignore @@ -17,6 +17,7 @@ coverage /plugin dayjs.min.js /esm +index.d.ts #dev demo.js diff --git a/.npmignore b/.npmignore index 4f08223c..1839a8b6 100644 --- a/.npmignore +++ b/.npmignore @@ -15,6 +15,7 @@ coverage # dev src test +types build .babelrc .eslintrc.json @@ -25,4 +26,4 @@ docs #other .travis.yml -karma.sauce.conf.js \ No newline at end of file +karma.sauce.conf.js diff --git a/build/index.js b/build/index.js index a5e08fda..0dd2e134 100644 --- a/build/index.js +++ b/build/index.js @@ -3,6 +3,7 @@ const configFactory = require('./rollup.config') const fs = require('fs') const util = require('util') const path = require('path') +const mergedirs = require('merge-dirs').default const { promisify } = util @@ -39,6 +40,8 @@ async function build(option) { input: './src/index.js', fileName: './dayjs.min.js' })) + + mergedirs('./types/', './', 'overwrite') } catch (e) { console.error(e) // eslint-disable-line no-console } diff --git a/package.json b/package.json index c600258e..acdf3ba8 100644 --- a/package.json +++ b/package.json @@ -6,7 +6,7 @@ "types": "index.d.ts", "module": "dayjs.min.js", "scripts": { - "test": "TZ=Pacific/Auckland npm run test-tz && TZ=Europe/London npm run test-tz && npm run test-tz && jest", + "test": "TZ=Pacific/Auckland npm run test-tz && TZ=Europe/London npm run test-tz && npm run test-tz && tsc && jest", "test-tz": "jest test/timezone.test --coverage=false", "lint": "./node_modules/.bin/eslint src/* test/* build/*", "prettier": "prettier --write \"docs/**/*.md\"", @@ -84,11 +84,12 @@ "karma": "^2.0.2", "karma-jasmine": "^1.1.2", "karma-sauce-launcher": "^1.1.0", + "merge-dirs": "^0.2.1", "mockdate": "^2.0.2", "moment": "^2.22.0", "pre-commit": "^1.2.2", "prettier": "^1.16.1", - "rollup": "^0.57.1", + "rollup": "^0.67.3", "rollup-plugin-babel": "^4.0.0-beta.4", "rollup-plugin-uglify": "^3.0.0", "size-limit": "^0.18.0", diff --git a/test/index.d.test.ts b/test/index.d.test.ts index 4e6edb44..ab800bab 100644 --- a/test/index.d.test.ts +++ b/test/index.d.test.ts @@ -1,4 +1,4 @@ -import dayjs from '../src' +import * as dayjs from 'dayjs' dayjs() @@ -8,6 +8,12 @@ dayjs(730944000000) dayjs(new Date(1993, 3, 1)) +dayjs('05/02/69 1:02:03 PM -05:00', 'MM/DD/YY H:mm:ss A Z') + +dayjs('05/02/69 1:02:03 PM -05:00', { format: 'MM/DD/YY H:mm:ss A Z' }) + +dayjs('1993-03-1', { locale: 'ja' }) + dayjs().clone() dayjs().isValid() @@ -70,10 +76,16 @@ dayjs().isSame(dayjs()) dayjs().isAfter(dayjs()) -dayjs().isBefore(dayjs(), 'minutes') +dayjs().isBefore(dayjs(), 'minute') -dayjs().isSame(dayjs(), 'hours') +dayjs().isSame(dayjs(), 'hour') dayjs().isAfter(dayjs(), 'year') dayjs('2000-01-01').isLeapYear() + +dayjs.extend((o, c, d) => { + o.locale.trim() + new c().unix() // eslint-disable-line new-cap + d().unix() +}) diff --git a/test/plugin/dayOfYear.d.test.ts b/test/plugin/dayOfYear.d.test.ts new file mode 100644 index 00000000..85173c66 --- /dev/null +++ b/test/plugin/dayOfYear.d.test.ts @@ -0,0 +1,6 @@ +import * as dayjs from 'dayjs' +import * as dayOfYear from 'dayjs/plugin/dayOfYear' + +dayjs.extend(dayOfYear) + +dayjs('2015-01-01T00:00:00.000').dayOfYear() === 1 diff --git a/test/plugin/isBetween.d.test.ts b/test/plugin/isBetween.d.test.ts new file mode 100644 index 00000000..4542e4b6 --- /dev/null +++ b/test/plugin/isBetween.d.test.ts @@ -0,0 +1,6 @@ +import * as dayjs from 'dayjs' +import * as isBetween from 'dayjs/plugin/isBetween' + +dayjs.extend(isBetween) + +dayjs('2010-10-20').isBetween('2010-10-19', dayjs('2010-10-25')) === true diff --git a/test/plugin/isLeapYear.d.test.ts b/test/plugin/isLeapYear.d.test.ts new file mode 100644 index 00000000..39993065 --- /dev/null +++ b/test/plugin/isLeapYear.d.test.ts @@ -0,0 +1,6 @@ +import * as dayjs from 'dayjs' +import * as isLeapYear from 'dayjs/plugin/isLeapYear' + +dayjs.extend(isLeapYear) + +dayjs('2010-10-20').isLeapYear() === false diff --git a/test/plugin/isSameOrAfter.d.test.ts b/test/plugin/isSameOrAfter.d.test.ts new file mode 100644 index 00000000..b8f257cf --- /dev/null +++ b/test/plugin/isSameOrAfter.d.test.ts @@ -0,0 +1,6 @@ +import * as dayjs from 'dayjs' +import * as isSameOrAfter from 'dayjs/plugin/isSameOrAfter' + +dayjs.extend(isSameOrAfter) + +dayjs('2010-10-20').isSameOrAfter('2010-10-19', 'year') === true diff --git a/test/plugin/isSameOrBefore.d.test.ts b/test/plugin/isSameOrBefore.d.test.ts new file mode 100644 index 00000000..5dcf966e --- /dev/null +++ b/test/plugin/isSameOrBefore.d.test.ts @@ -0,0 +1,6 @@ +import * as dayjs from 'dayjs' +import * as isSameOrBefore from 'dayjs/plugin/isSameOrBefore' + +dayjs.extend(isSameOrBefore) + +dayjs('2010-10-20').isSameOrBefore('2010-10-19', 'year') === true diff --git a/test/plugin/quarterOfYear.d.test.ts b/test/plugin/quarterOfYear.d.test.ts new file mode 100644 index 00000000..f3f2b8ae --- /dev/null +++ b/test/plugin/quarterOfYear.d.test.ts @@ -0,0 +1,6 @@ +import * as dayjs from 'dayjs' +import * as quarterOfYear from 'dayjs/plugin/quarterOfYear' + +dayjs.extend(quarterOfYear) + +dayjs('2013-01-01T00:00:00.000').quarter() === 1 diff --git a/test/plugin/relativeTime.d.test.ts b/test/plugin/relativeTime.d.test.ts new file mode 100644 index 00000000..1124553f --- /dev/null +++ b/test/plugin/relativeTime.d.test.ts @@ -0,0 +1,20 @@ +import * as dayjs from 'dayjs' +import * as relativeTime from 'dayjs/plugin/relativeTime' + +dayjs.extend(relativeTime) + +dayjs().fromNow().trim() +dayjs().fromNow(true).trim() + +dayjs().from(dayjs()).trim() +dayjs().from(123, true).trim() +dayjs().from('2018-01-23').trim() +dayjs().from(new Date(), true).trim() + +dayjs().toNow().trim() +dayjs().toNow(true).trim() + +dayjs().to(dayjs()).trim() +dayjs().to(123, true).trim() +dayjs().to('2018-01-23').trim() +dayjs().to(new Date(), true).trim() diff --git a/test/plugin/weekOfYear.d.test.ts b/test/plugin/weekOfYear.d.test.ts new file mode 100644 index 00000000..bfaceede --- /dev/null +++ b/test/plugin/weekOfYear.d.test.ts @@ -0,0 +1,6 @@ +import * as dayjs from 'dayjs' +import * as weekOfYear from 'dayjs/plugin/weekOfYear' + +dayjs.extend(weekOfYear) + +dayjs('2010-10-20').week() === 43 diff --git a/tsconfig.json b/tsconfig.json new file mode 100644 index 00000000..c79e47e2 --- /dev/null +++ b/tsconfig.json @@ -0,0 +1,20 @@ +{ + "compilerOptions": { + "strict": true, + "noEmit": true, + "lib": [ + // TODO: Unfortunately, rollup brings @types/node and etc. with "dependencies", not "devDependencies". + // It references Symbol type. + "es5", + "es2015.symbol" + ], + "baseUrl": "./types", + "paths": { + "dayjs": [ "." ], + "dayjs/*": [ "*" ] + } + }, + "exclude": [ + "node_modules" + ] +} diff --git a/index.d.ts b/types/index.d.ts similarity index 58% rename from index.d.ts rename to types/index.d.ts index 236a7d27..e1733a90 100644 --- a/index.d.ts +++ b/types/index.d.ts @@ -1,10 +1,13 @@ export = dayjs; -declare function dayjs (config?: dayjs.ConfigType, option?: dayjs.OptionType): dayjs.Dayjs +declare function dayjs (date?: dayjs.DateType, option?: dayjs.OptionType): dayjs.Dayjs declare namespace dayjs { - export type ConfigType = string | number | Date | Dayjs + export type DateType = string | number | Date | Dayjs - export type OptionType = { locale: string } + /** @deprecated Renamed to DateType. */ + export type ConfigType = DateType + + export type OptionType = { locale?: string, format?: string } | string type UnitTypeShort = 'd' | 'M' | 'y' | 'h' | 'm' | 's' | 'ms' export type UnitType = 'millisecond' | 'second' | 'minute' | 'hour' | 'day' | 'month' | 'quarter' | 'year' | 'date' | UnitTypeShort; @@ -23,7 +26,7 @@ declare namespace dayjs { } class Dayjs { - constructor (config?: ConfigType) + constructor (date?: DateType) clone(): Dayjs @@ -57,7 +60,7 @@ declare namespace dayjs { format(template?: string): string - diff(dayjs: ConfigType, unit: OpUnitType, float?: boolean): number + diff(date: DateType, unit: OpUnitType, float?: boolean): number valueOf(): number @@ -77,24 +80,24 @@ declare namespace dayjs { toString(): string - isBefore(dayjs: ConfigType, unit?: OpUnitType): boolean + isBefore(date: DateType, unit?: OpUnitType): boolean - isSame(dayjs: ConfigType, unit?: OpUnitType): boolean + isSame(date: DateType, unit?: OpUnitType): boolean - isAfter(dayjs: ConfigType, unit?: OpUnitType): boolean + isAfter(date: DateType, unit?: OpUnitType): boolean isLeapYear(): boolean - locale(arg1: any, arg2?: any): Dayjs + locale(preset: string | { name: string, [key: string]: any }, object?: { [key: string]: any }): Dayjs } - export type PluginFunc = (option: ConfigType, d1: Dayjs, d2: Dayjs) => void + export type PluginFunc = (option: any, c: typeof Dayjs, d: typeof dayjs) => void - export function extend(plugin: PluginFunc, option?: ConfigType): Dayjs + export function extend(plugin: PluginFunc, option?: any): Dayjs - export function locale(arg1: any, arg2?: any): string + export function locale(preset: string | { name: string, [key: string]: any }, object?: { [key: string]: any }, isLocal?: boolean): string export function isDayjs(d: any): d is Dayjs - + export function unix(t: number): Dayjs } diff --git a/types/plugin/advancedFormat.d.ts b/types/plugin/advancedFormat.d.ts new file mode 100644 index 00000000..30ec75e5 --- /dev/null +++ b/types/plugin/advancedFormat.d.ts @@ -0,0 +1,4 @@ +import { PluginFunc } from 'dayjs' + +declare const plugin: PluginFunc +export = plugin diff --git a/types/plugin/buddhistEra.d.ts b/types/plugin/buddhistEra.d.ts new file mode 100644 index 00000000..30ec75e5 --- /dev/null +++ b/types/plugin/buddhistEra.d.ts @@ -0,0 +1,4 @@ +import { PluginFunc } from 'dayjs' + +declare const plugin: PluginFunc +export = plugin diff --git a/types/plugin/customParseFormat.ts b/types/plugin/customParseFormat.ts new file mode 100644 index 00000000..30ec75e5 --- /dev/null +++ b/types/plugin/customParseFormat.ts @@ -0,0 +1,4 @@ +import { PluginFunc } from 'dayjs' + +declare const plugin: PluginFunc +export = plugin diff --git a/types/plugin/dayOfYear.d.ts b/types/plugin/dayOfYear.d.ts new file mode 100644 index 00000000..02838515 --- /dev/null +++ b/types/plugin/dayOfYear.d.ts @@ -0,0 +1,10 @@ +import { PluginFunc } from 'dayjs' + +declare const plugin: PluginFunc +export = plugin + +declare module 'dayjs' { + interface Dayjs { + dayOfYear(): number + } +} diff --git a/types/plugin/isBetween.d.ts b/types/plugin/isBetween.d.ts new file mode 100644 index 00000000..41afb64c --- /dev/null +++ b/types/plugin/isBetween.d.ts @@ -0,0 +1,10 @@ +import { PluginFunc, DateType } from 'dayjs' + +declare const plugin: PluginFunc +export = plugin + +declare module 'dayjs' { + interface Dayjs { + isBetween(a: DateType, b: DateType): boolean + } +} diff --git a/types/plugin/isLeapYear.d.ts b/types/plugin/isLeapYear.d.ts new file mode 100644 index 00000000..5be74092 --- /dev/null +++ b/types/plugin/isLeapYear.d.ts @@ -0,0 +1,10 @@ +import { PluginFunc } from 'dayjs' + +declare const plugin: PluginFunc +export = plugin + +declare module 'dayjs' { + interface Dayjs { + isLeapYear(): boolean + } +} diff --git a/types/plugin/isSameOrAfter.d.ts b/types/plugin/isSameOrAfter.d.ts new file mode 100644 index 00000000..12d6f889 --- /dev/null +++ b/types/plugin/isSameOrAfter.d.ts @@ -0,0 +1,10 @@ +import { PluginFunc } from 'dayjs' + +declare const plugin: PluginFunc +export = plugin + +declare module 'dayjs' { + interface Dayjs { + isSameOrAfter(date: DateType, unit?: OpUnitType): boolean + } +} diff --git a/types/plugin/isSameOrBefore.d.ts b/types/plugin/isSameOrBefore.d.ts new file mode 100644 index 00000000..3442c69a --- /dev/null +++ b/types/plugin/isSameOrBefore.d.ts @@ -0,0 +1,10 @@ +import { PluginFunc } from 'dayjs' + +declare const plugin: PluginFunc +export = plugin + +declare module 'dayjs' { + interface Dayjs { + isSameOrBefore(date: DateType, unit?: OpUnitType): boolean + } +} diff --git a/types/plugin/localizedFormat.d.ts b/types/plugin/localizedFormat.d.ts new file mode 100644 index 00000000..30ec75e5 --- /dev/null +++ b/types/plugin/localizedFormat.d.ts @@ -0,0 +1,4 @@ +import { PluginFunc } from 'dayjs' + +declare const plugin: PluginFunc +export = plugin diff --git a/types/plugin/quarterOfYear.d.ts b/types/plugin/quarterOfYear.d.ts new file mode 100644 index 00000000..e8aad14b --- /dev/null +++ b/types/plugin/quarterOfYear.d.ts @@ -0,0 +1,10 @@ +import { PluginFunc } from 'dayjs' + +declare const plugin: PluginFunc +export = plugin + +declare module 'dayjs' { + interface Dayjs { + quarter(): number + } +} diff --git a/types/plugin/relativeTime.d.ts b/types/plugin/relativeTime.d.ts new file mode 100644 index 00000000..30649300 --- /dev/null +++ b/types/plugin/relativeTime.d.ts @@ -0,0 +1,13 @@ +import { PluginFunc, DateType } from 'dayjs' + +declare const plugin: PluginFunc +export = plugin + +declare module 'dayjs' { + interface Dayjs { + fromNow(withoutSuffix?: boolean): string + from(compared: DateType, withoutSuffix?: boolean): string + toNow(withoutSuffix?: boolean): string + to(compared: DateType, withoutSuffix?: boolean): string + } +} diff --git a/types/plugin/weekOfYear.d.ts b/types/plugin/weekOfYear.d.ts new file mode 100644 index 00000000..36021955 --- /dev/null +++ b/types/plugin/weekOfYear.d.ts @@ -0,0 +1,10 @@ +import { PluginFunc } from 'dayjs' + +declare const plugin: PluginFunc +export = plugin + +declare module 'dayjs' { + interface Dayjs { + week(): number + } +} From 185fe328aaeb825a52a8cc1121d4d2ca9d138959 Mon Sep 17 00:00:00 2001 From: splashwizard Date: Sat, 23 Feb 2019 23:16:37 +0800 Subject: [PATCH 11/25] chore: rm ts test temporary --- package.json | 4 +- test/index.d.test.ts | 91 ---------------------------- test/plugin/dayOfYear.d.test.ts | 6 -- test/plugin/isBetween.d.test.ts | 6 -- test/plugin/isLeapYear.d.test.ts | 6 -- test/plugin/isSameOrAfter.d.test.ts | 6 -- test/plugin/isSameOrBefore.d.test.ts | 6 -- test/plugin/quarterOfYear.d.test.ts | 6 -- test/plugin/relativeTime.d.test.ts | 20 ------ test/plugin/weekOfYear.d.test.ts | 6 -- tsconfig.json | 20 ------ 11 files changed, 2 insertions(+), 175 deletions(-) delete mode 100644 test/index.d.test.ts delete mode 100644 test/plugin/dayOfYear.d.test.ts delete mode 100644 test/plugin/isBetween.d.test.ts delete mode 100644 test/plugin/isLeapYear.d.test.ts delete mode 100644 test/plugin/isSameOrAfter.d.test.ts delete mode 100644 test/plugin/isSameOrBefore.d.test.ts delete mode 100644 test/plugin/quarterOfYear.d.test.ts delete mode 100644 test/plugin/relativeTime.d.test.ts delete mode 100644 test/plugin/weekOfYear.d.test.ts delete mode 100644 tsconfig.json diff --git a/package.json b/package.json index acdf3ba8..00ff83e1 100644 --- a/package.json +++ b/package.json @@ -6,7 +6,7 @@ "types": "index.d.ts", "module": "dayjs.min.js", "scripts": { - "test": "TZ=Pacific/Auckland npm run test-tz && TZ=Europe/London npm run test-tz && npm run test-tz && tsc && jest", + "test": "TZ=Pacific/Auckland npm run test-tz && TZ=Europe/London npm run test-tz && npm run test-tz && jest", "test-tz": "jest test/timezone.test --coverage=false", "lint": "./node_modules/.bin/eslint src/* test/* build/*", "prettier": "prettier --write \"docs/**/*.md\"", @@ -89,7 +89,7 @@ "moment": "^2.22.0", "pre-commit": "^1.2.2", "prettier": "^1.16.1", - "rollup": "^0.67.3", + "rollup": "^0.57.1", "rollup-plugin-babel": "^4.0.0-beta.4", "rollup-plugin-uglify": "^3.0.0", "size-limit": "^0.18.0", diff --git a/test/index.d.test.ts b/test/index.d.test.ts deleted file mode 100644 index ab800bab..00000000 --- a/test/index.d.test.ts +++ /dev/null @@ -1,91 +0,0 @@ -import * as dayjs from 'dayjs' - -dayjs() - -dayjs('1993-03-1') - -dayjs(730944000000) - -dayjs(new Date(1993, 3, 1)) - -dayjs('05/02/69 1:02:03 PM -05:00', 'MM/DD/YY H:mm:ss A Z') - -dayjs('05/02/69 1:02:03 PM -05:00', { format: 'MM/DD/YY H:mm:ss A Z' }) - -dayjs('1993-03-1', { locale: 'ja' }) - -dayjs().clone() - -dayjs().isValid() - -dayjs().year() - -dayjs().month() - -dayjs().date() - -dayjs().day() - -dayjs().hour() - -dayjs().minute() - -dayjs().second() - -dayjs().millisecond() - -dayjs().set('month', 3) -dayjs().set('second', 30) - -dayjs().add(7, 'day') - -dayjs().subtract(7, 'year') - -dayjs().startOf('year') - -dayjs().endOf('month') - -dayjs().startOf('month').add(1, 'day').subtract(1, 'year') - -dayjs().format() -dayjs().format('[YYYY] MM-DDTHH:mm:ssZ') - -dayjs().diff(dayjs(), 'year') - -dayjs().valueOf() - -dayjs().unix() - -dayjs().daysInMonth() - -dayjs().toDate() - -dayjs().toArray() - -dayjs().toJSON() - -dayjs().toISOString() - -dayjs().toObject() - -dayjs().toString() - -dayjs().isBefore(dayjs()) - -dayjs().isSame(dayjs()) - -dayjs().isAfter(dayjs()) - -dayjs().isBefore(dayjs(), 'minute') - -dayjs().isSame(dayjs(), 'hour') - -dayjs().isAfter(dayjs(), 'year') - -dayjs('2000-01-01').isLeapYear() - -dayjs.extend((o, c, d) => { - o.locale.trim() - new c().unix() // eslint-disable-line new-cap - d().unix() -}) diff --git a/test/plugin/dayOfYear.d.test.ts b/test/plugin/dayOfYear.d.test.ts deleted file mode 100644 index 85173c66..00000000 --- a/test/plugin/dayOfYear.d.test.ts +++ /dev/null @@ -1,6 +0,0 @@ -import * as dayjs from 'dayjs' -import * as dayOfYear from 'dayjs/plugin/dayOfYear' - -dayjs.extend(dayOfYear) - -dayjs('2015-01-01T00:00:00.000').dayOfYear() === 1 diff --git a/test/plugin/isBetween.d.test.ts b/test/plugin/isBetween.d.test.ts deleted file mode 100644 index 4542e4b6..00000000 --- a/test/plugin/isBetween.d.test.ts +++ /dev/null @@ -1,6 +0,0 @@ -import * as dayjs from 'dayjs' -import * as isBetween from 'dayjs/plugin/isBetween' - -dayjs.extend(isBetween) - -dayjs('2010-10-20').isBetween('2010-10-19', dayjs('2010-10-25')) === true diff --git a/test/plugin/isLeapYear.d.test.ts b/test/plugin/isLeapYear.d.test.ts deleted file mode 100644 index 39993065..00000000 --- a/test/plugin/isLeapYear.d.test.ts +++ /dev/null @@ -1,6 +0,0 @@ -import * as dayjs from 'dayjs' -import * as isLeapYear from 'dayjs/plugin/isLeapYear' - -dayjs.extend(isLeapYear) - -dayjs('2010-10-20').isLeapYear() === false diff --git a/test/plugin/isSameOrAfter.d.test.ts b/test/plugin/isSameOrAfter.d.test.ts deleted file mode 100644 index b8f257cf..00000000 --- a/test/plugin/isSameOrAfter.d.test.ts +++ /dev/null @@ -1,6 +0,0 @@ -import * as dayjs from 'dayjs' -import * as isSameOrAfter from 'dayjs/plugin/isSameOrAfter' - -dayjs.extend(isSameOrAfter) - -dayjs('2010-10-20').isSameOrAfter('2010-10-19', 'year') === true diff --git a/test/plugin/isSameOrBefore.d.test.ts b/test/plugin/isSameOrBefore.d.test.ts deleted file mode 100644 index 5dcf966e..00000000 --- a/test/plugin/isSameOrBefore.d.test.ts +++ /dev/null @@ -1,6 +0,0 @@ -import * as dayjs from 'dayjs' -import * as isSameOrBefore from 'dayjs/plugin/isSameOrBefore' - -dayjs.extend(isSameOrBefore) - -dayjs('2010-10-20').isSameOrBefore('2010-10-19', 'year') === true diff --git a/test/plugin/quarterOfYear.d.test.ts b/test/plugin/quarterOfYear.d.test.ts deleted file mode 100644 index f3f2b8ae..00000000 --- a/test/plugin/quarterOfYear.d.test.ts +++ /dev/null @@ -1,6 +0,0 @@ -import * as dayjs from 'dayjs' -import * as quarterOfYear from 'dayjs/plugin/quarterOfYear' - -dayjs.extend(quarterOfYear) - -dayjs('2013-01-01T00:00:00.000').quarter() === 1 diff --git a/test/plugin/relativeTime.d.test.ts b/test/plugin/relativeTime.d.test.ts deleted file mode 100644 index 1124553f..00000000 --- a/test/plugin/relativeTime.d.test.ts +++ /dev/null @@ -1,20 +0,0 @@ -import * as dayjs from 'dayjs' -import * as relativeTime from 'dayjs/plugin/relativeTime' - -dayjs.extend(relativeTime) - -dayjs().fromNow().trim() -dayjs().fromNow(true).trim() - -dayjs().from(dayjs()).trim() -dayjs().from(123, true).trim() -dayjs().from('2018-01-23').trim() -dayjs().from(new Date(), true).trim() - -dayjs().toNow().trim() -dayjs().toNow(true).trim() - -dayjs().to(dayjs()).trim() -dayjs().to(123, true).trim() -dayjs().to('2018-01-23').trim() -dayjs().to(new Date(), true).trim() diff --git a/test/plugin/weekOfYear.d.test.ts b/test/plugin/weekOfYear.d.test.ts deleted file mode 100644 index bfaceede..00000000 --- a/test/plugin/weekOfYear.d.test.ts +++ /dev/null @@ -1,6 +0,0 @@ -import * as dayjs from 'dayjs' -import * as weekOfYear from 'dayjs/plugin/weekOfYear' - -dayjs.extend(weekOfYear) - -dayjs('2010-10-20').week() === 43 diff --git a/tsconfig.json b/tsconfig.json deleted file mode 100644 index c79e47e2..00000000 --- a/tsconfig.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "compilerOptions": { - "strict": true, - "noEmit": true, - "lib": [ - // TODO: Unfortunately, rollup brings @types/node and etc. with "dependencies", not "devDependencies". - // It references Symbol type. - "es5", - "es2015.symbol" - ], - "baseUrl": "./types", - "paths": { - "dayjs": [ "." ], - "dayjs/*": [ "*" ] - } - }, - "exclude": [ - "node_modules" - ] -} From e932a5da9ad4529214425621fdc316a1e7322008 Mon Sep 17 00:00:00 2001 From: splashwizard Date: Sat, 23 Feb 2019 23:47:38 +0800 Subject: [PATCH 12/25] test: add plugin declaration exist test --- test/plugin/declarations.test.js | 13 +++++++++++++ ...{customParseFormat.ts => customParseFormat.d.ts} | 0 2 files changed, 13 insertions(+) create mode 100644 test/plugin/declarations.test.js rename types/plugin/{customParseFormat.ts => customParseFormat.d.ts} (100%) diff --git a/test/plugin/declarations.test.js b/test/plugin/declarations.test.js new file mode 100644 index 00000000..b8bfb51c --- /dev/null +++ b/test/plugin/declarations.test.js @@ -0,0 +1,13 @@ +import fs from 'fs' +import path from 'path' + +const pluginDir = '../../src/plugin' +const pluginTypeDir = '../../types/plugin' + +it('Plugin declarations', () => { + fs.readdirSync(path.join(__dirname, pluginDir)) + .forEach((l) => { + expect(fs.existsSync(path.join(__dirname, pluginTypeDir, `${l}.d.ts`))) + .toBe(true) + }) +}) diff --git a/types/plugin/customParseFormat.ts b/types/plugin/customParseFormat.d.ts similarity index 100% rename from types/plugin/customParseFormat.ts rename to types/plugin/customParseFormat.d.ts From 22196b7840df156832e0dd07596e11f083c05608 Mon Sep 17 00:00:00 2001 From: splashwizard Date: Sun, 24 Feb 2019 00:05:35 +0800 Subject: [PATCH 13/25] build: switch to ncp --- build/index.js | 6 ++++-- package.json | 2 +- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/build/index.js b/build/index.js index 0dd2e134..b86f75b7 100644 --- a/build/index.js +++ b/build/index.js @@ -3,7 +3,7 @@ const configFactory = require('./rollup.config') const fs = require('fs') const util = require('util') const path = require('path') -const mergedirs = require('merge-dirs').default +const { ncp } = require('ncp') const { promisify } = util @@ -41,7 +41,9 @@ async function build(option) { fileName: './dayjs.min.js' })) - mergedirs('./types/', './', 'overwrite') + ncp('./types/', './', (err) => { + if (err) { throw err } + }) } catch (e) { console.error(e) // eslint-disable-line no-console } diff --git a/package.json b/package.json index 00ff83e1..e7f2af7a 100644 --- a/package.json +++ b/package.json @@ -84,9 +84,9 @@ "karma": "^2.0.2", "karma-jasmine": "^1.1.2", "karma-sauce-launcher": "^1.1.0", - "merge-dirs": "^0.2.1", "mockdate": "^2.0.2", "moment": "^2.22.0", + "ncp": "^2.0.0", "pre-commit": "^1.2.2", "prettier": "^1.16.1", "rollup": "^0.57.1", From 3febebb194ec0d0ef95293aa4e40f8b119b6f47e Mon Sep 17 00:00:00 2001 From: splashwizard Date: Sun, 24 Feb 2019 00:25:40 +0800 Subject: [PATCH 14/25] chore: Update index.d.ts --- types/index.d.ts | 17 +++++++---------- 1 file changed, 7 insertions(+), 10 deletions(-) diff --git a/types/index.d.ts b/types/index.d.ts index e1733a90..5d428b73 100644 --- a/types/index.d.ts +++ b/types/index.d.ts @@ -1,11 +1,8 @@ export = dayjs; -declare function dayjs (date?: dayjs.DateType, option?: dayjs.OptionType): dayjs.Dayjs +declare function dayjs (date?: dayjs.ConfigType, option?: dayjs.OptionType): dayjs.Dayjs declare namespace dayjs { - export type DateType = string | number | Date | Dayjs - - /** @deprecated Renamed to DateType. */ - export type ConfigType = DateType + export type ConfigType = string | number | Date | Dayjs export type OptionType = { locale?: string, format?: string } | string @@ -26,7 +23,7 @@ declare namespace dayjs { } class Dayjs { - constructor (date?: DateType) + constructor (config?: ConfigType) clone(): Dayjs @@ -60,7 +57,7 @@ declare namespace dayjs { format(template?: string): string - diff(date: DateType, unit: OpUnitType, float?: boolean): number + diff(date: ConfigType, unit: OpUnitType, float?: boolean): number valueOf(): number @@ -80,11 +77,11 @@ declare namespace dayjs { toString(): string - isBefore(date: DateType, unit?: OpUnitType): boolean + isBefore(date: ConfigType, unit?: OpUnitType): boolean - isSame(date: DateType, unit?: OpUnitType): boolean + isSame(date: ConfigType, unit?: OpUnitType): boolean - isAfter(date: DateType, unit?: OpUnitType): boolean + isAfter(date: ConfigType, unit?: OpUnitType): boolean isLeapYear(): boolean From 79f458aa9d3f87cb8405c81b2210d0937a4fe5d0 Mon Sep 17 00:00:00 2001 From: splashwizard Date: Sun, 24 Feb 2019 00:31:09 +0800 Subject: [PATCH 15/25] chore: update d.ts --- types/index.d.ts | 2 -- types/plugin/isBetween.d.ts | 4 ++-- types/plugin/isSameOrAfter.d.ts | 4 ++-- types/plugin/isSameOrBefore.d.ts | 4 ++-- 4 files changed, 6 insertions(+), 8 deletions(-) diff --git a/types/index.d.ts b/types/index.d.ts index 5d428b73..24ac01f1 100644 --- a/types/index.d.ts +++ b/types/index.d.ts @@ -83,8 +83,6 @@ declare namespace dayjs { isAfter(date: ConfigType, unit?: OpUnitType): boolean - isLeapYear(): boolean - locale(preset: string | { name: string, [key: string]: any }, object?: { [key: string]: any }): Dayjs } diff --git a/types/plugin/isBetween.d.ts b/types/plugin/isBetween.d.ts index 41afb64c..9500c495 100644 --- a/types/plugin/isBetween.d.ts +++ b/types/plugin/isBetween.d.ts @@ -1,10 +1,10 @@ -import { PluginFunc, DateType } from 'dayjs' +import { PluginFunc, ConfigType } from 'dayjs' declare const plugin: PluginFunc export = plugin declare module 'dayjs' { interface Dayjs { - isBetween(a: DateType, b: DateType): boolean + isBetween(a: ConfigType, b: ConfigType): boolean } } diff --git a/types/plugin/isSameOrAfter.d.ts b/types/plugin/isSameOrAfter.d.ts index 12d6f889..1c8c2649 100644 --- a/types/plugin/isSameOrAfter.d.ts +++ b/types/plugin/isSameOrAfter.d.ts @@ -1,10 +1,10 @@ -import { PluginFunc } from 'dayjs' +import { PluginFunc, ConfigType, OpUnitType } from 'dayjs' declare const plugin: PluginFunc export = plugin declare module 'dayjs' { interface Dayjs { - isSameOrAfter(date: DateType, unit?: OpUnitType): boolean + isSameOrAfter(date: ConfigType, unit?: OpUnitType): boolean } } diff --git a/types/plugin/isSameOrBefore.d.ts b/types/plugin/isSameOrBefore.d.ts index 3442c69a..1df5492c 100644 --- a/types/plugin/isSameOrBefore.d.ts +++ b/types/plugin/isSameOrBefore.d.ts @@ -1,10 +1,10 @@ -import { PluginFunc } from 'dayjs' +import { PluginFunc, ConfigType, OpUnitType } from 'dayjs' declare const plugin: PluginFunc export = plugin declare module 'dayjs' { interface Dayjs { - isSameOrBefore(date: DateType, unit?: OpUnitType): boolean + isSameOrBefore(date: ConfigType, unit?: OpUnitType): boolean } } From 84240162619adfc14cd9655d83d2c29d62784ea8 Mon Sep 17 00:00:00 2001 From: splashwizard Date: Sun, 24 Feb 2019 00:55:44 +0800 Subject: [PATCH 16/25] chore: update isBetween.d.ts --- types/plugin/isBetween.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/types/plugin/isBetween.d.ts b/types/plugin/isBetween.d.ts index 9500c495..e73a27ec 100644 --- a/types/plugin/isBetween.d.ts +++ b/types/plugin/isBetween.d.ts @@ -1,10 +1,10 @@ -import { PluginFunc, ConfigType } from 'dayjs' +import { PluginFunc, ConfigType, OpUnitType } from 'dayjs' declare const plugin: PluginFunc export = plugin declare module 'dayjs' { interface Dayjs { - isBetween(a: ConfigType, b: ConfigType): boolean + isBetween(a: ConfigType, b: ConfigType, c?: OpUnitType | null, d?: string): boolean } } From da758c8e5a90e9f0b997a6d2c240a52a5cd5194c Mon Sep 17 00:00:00 2001 From: Sergey Sharov Date: Sat, 23 Feb 2019 20:05:16 +0300 Subject: [PATCH 17/25] fix: Parse month string 'MMMM MMM (February, Feb)' in customParseFormat (#457) --- .babelrc => babel.config.js | 40 ++++++++++---------- docs/en/Plugin.md | 3 ++ docs/es-es/Plugin.md | 17 +++++++++ docs/ja/Plugin.md | 3 ++ docs/ko/Plugin.md | 3 ++ docs/pt-br/Plugin.md | 3 ++ docs/zh-cn/Plugin.md | 3 ++ src/index.js | 6 +-- src/plugin/customParseFormat/index.js | 24 +++++++++++- test/plugin/customParseFormat.test.js | 54 +++++++++++++++++++++++++++ 10 files changed, 132 insertions(+), 24 deletions(-) rename .babelrc => babel.config.js (87%) diff --git a/.babelrc b/babel.config.js similarity index 87% rename from .babelrc rename to babel.config.js index 6ae4011d..a0291dac 100644 --- a/.babelrc +++ b/babel.config.js @@ -1,20 +1,20 @@ -{ - "env": { - "test": { - "presets": [ - "@babel/preset-env" - ] - }, - "build": { - "presets": [ - [ - "@babel/preset-env", - { - "modules": false, - "loose": true - } - ] - ] - } - } -} +module.exports = { + "env": { + "test": { + "presets": [ + "@babel/preset-env" + ] + }, + "build": { + "presets": [ + [ + "@babel/preset-env", + { + "modules": false, + "loose": true + } + ] + ] + } + } +}; \ No newline at end of file diff --git a/docs/en/Plugin.md b/docs/en/Plugin.md index 7df564c7..ea00de43 100644 --- a/docs/en/Plugin.md +++ b/docs/en/Plugin.md @@ -260,6 +260,9 @@ dayjs.extend(customParseFormat) dayjs('05/02/69 1:02:03 PM -05:00', 'MM/DD/YY H:mm:ss A Z') // Returns an instance containing '1969-05-02T18:02:03.000Z' + +dayjs('2018 Enero 15', { format: 'YYYY MMMM DD', locale: es }) +// Returns an instance containing '2018-01-15T00:00:00.000Z' ``` #### List of all available format tokens diff --git a/docs/es-es/Plugin.md b/docs/es-es/Plugin.md index aede05fd..5668155b 100644 --- a/docs/es-es/Plugin.md +++ b/docs/es-es/Plugin.md @@ -247,6 +247,23 @@ dayjs.extend(quarterOfYear) dayjs('2010-04-01').quarter() // 2 ``` +### CustomParseFormat + - CustomParseFormat extends `dayjs()` constructor to support custom formats of input strings. + +To escape characters, wrap them in square brackets (e.g. `[G]`). Punctuation symbols (-:/.()) do not need to be wrapped. + +```javascript +import customParseFormat from 'dayjs/plugin/customParseFormat' + +dayjs.extend(customParseFormat) + +dayjs('05/02/69 1:02:03 PM -05:00', 'MM/DD/YY H:mm:ss A Z') +// Returns an instance containing '1969-05-02T18:02:03.000Z' + +dayjs('2018 Enero 15', { format: 'YYYY MMMM DD', locale: es }) +// Returns an instance containing '2018-01-15T00:00:00.000Z' +``` + #### List of all available format tokens | Format | Output | Description | diff --git a/docs/ja/Plugin.md b/docs/ja/Plugin.md index 4be8f2e4..981a29e2 100644 --- a/docs/ja/Plugin.md +++ b/docs/ja/Plugin.md @@ -269,6 +269,9 @@ dayjs.extend(customParseFormat) dayjs('05/02/69 1:02:03 PM -05:00', 'MM/DD/YY H:mm:ss A Z') // Returns an instance containing '1969-05-02T18:02:03.000Z' + +dayjs('2018 5月 15', { format: 'YYYY MMMM DD', locale: ja }) +// Returns an instance containing '2018-05-15T00:00:00.000Z' ``` #### List of all available format tokens diff --git a/docs/ko/Plugin.md b/docs/ko/Plugin.md index cd96ff2d..e203c811 100644 --- a/docs/ko/Plugin.md +++ b/docs/ko/Plugin.md @@ -261,6 +261,9 @@ dayjs.extend(customParseFormat) dayjs('05/02/69 1:02:03 PM -05:00', 'MM/DD/YY H:mm:ss A Z') // Returns an instance containing '1969-05-02T18:02:03.000Z' + +dayjs('2018 5월 15', { format: 'YYYY MMMM DD', locale: ko }) +// Returns an instance containing '2018-05-15T00:00:00.000Z' ``` #### List of all available format tokens diff --git a/docs/pt-br/Plugin.md b/docs/pt-br/Plugin.md index 0d600048..04581f34 100644 --- a/docs/pt-br/Plugin.md +++ b/docs/pt-br/Plugin.md @@ -260,6 +260,9 @@ dayjs.extend(customParseFormat) dayjs('05/02/69 1:02:03 PM -05:00', 'MM/DD/YY H:mm:ss A Z') // Returns an instance containing '1969-05-02T18:02:03.000Z' + +dayjs('2018 Fevereiro 15', { format: 'YYYY MMMM DD', locale: pt_br }) +// Returns an instance containing '2018-02-15T00:00:00.000Z' ``` #### List of all available format tokens diff --git a/docs/zh-cn/Plugin.md b/docs/zh-cn/Plugin.md index 3ce2cd1c..02938ab3 100644 --- a/docs/zh-cn/Plugin.md +++ b/docs/zh-cn/Plugin.md @@ -260,6 +260,9 @@ dayjs.extend(customParseFormat) dayjs('05/02/69 1:02:03 PM -05:00', 'MM/DD/YY H:mm:ss A Z') // Returns an instance containing '1969-05-02T18:02:03.000Z' + +dayjs('2018 五月 15', { format: 'YYYY MMMM DD', locale: zh_cn }) +// Returns an instance containing '2018-05-15T00:00:00.000Z' ``` #### List of all available format tokens diff --git a/src/index.js b/src/index.js index 2e2cdbdb..e33a80a0 100644 --- a/src/index.js +++ b/src/index.js @@ -61,15 +61,16 @@ const parseDate = (date) => { class Dayjs { constructor(cfg) { + this.$L = this.$L || parseLocale(cfg.locale, null, true) || L this.parse(cfg) // for plugin } parse(cfg) { this.$d = parseDate(cfg.date) - this.init(cfg) + this.init() } - init(cfg) { + init() { const { $d } = this this.$y = $d.getFullYear() this.$M = $d.getMonth() @@ -79,7 +80,6 @@ class Dayjs { this.$m = $d.getMinutes() this.$s = $d.getSeconds() this.$ms = $d.getMilliseconds() - this.$L = this.$L || parseLocale(cfg.locale, null, true) || L } // eslint-disable-next-line class-methods-use-this diff --git a/src/plugin/customParseFormat/index.js b/src/plugin/customParseFormat/index.js index ad639beb..0d8e0acb 100644 --- a/src/plugin/customParseFormat/index.js +++ b/src/plugin/customParseFormat/index.js @@ -1,4 +1,4 @@ -const formattingTokens = /(\[[^[]*\])|([-:/.()\s]+)|(A|a|YYYY|YY?|MM?|DD?|hh?|HH?|mm?|ss?|S{1,3}|z|ZZ?)/g +const formattingTokens = /(\[[^[]*\])|([-:/.()\s]+)|(A|a|YYYY|YY?|MM?M?M?|DD?|hh?|HH?|mm?|ss?|S{1,3}|z|ZZ?)/g const match1 = /\d/ // 0 - 9 const match2 = /\d\d/ // 00 - 99 @@ -9,6 +9,9 @@ const matchUpperCaseAMPM = /[AP]M/ const matchLowerCaseAMPM = /[ap]m/ const matchSigned = /[+-]?\d+/ // -inf - inf const matchOffset = /[+-]\d\d:?\d\d/ // +00:00 -00:00 +0000 or -0000 +const matchWord = /\d*[^\s\d]+/ // Word + +let locale function offsetFromString(string) { const parts = string.match(/([+-]|\d\d)/g) @@ -55,6 +58,24 @@ const expressions = { DD: [match2, addInput('day')], M: [match1to2, addInput('month')], MM: [match2, addInput('month')], + MMM: [matchWord, function (input) { + const { months, monthsShort } = locale + const matchIndex = monthsShort + ? monthsShort.findIndex(month => month === input) + : months.findIndex(month => month.substr(0, 3) === input) + if (matchIndex < 0) { + throw new Error() + } + this.month = matchIndex + 1 + }], + MMMM: [matchWord, function (input) { + const { months } = locale + const matchIndex = months.indexOf(input) + if (matchIndex < 0) { + throw new Error() + } + this.month = matchIndex + 1 + }], Y: [matchSigned, addInput('year')], YY: [match2, function (input) { input = +input @@ -144,6 +165,7 @@ export default (o, C) => { proto.parse = function (cfg) { const { date: input, format } = cfg if (format) { + locale = this.$locale() this.$d = parseFormattedInput(input, format) this.init(cfg) } else { diff --git a/test/plugin/customParseFormat.test.js b/test/plugin/customParseFormat.test.js index e26cbea3..b278462f 100644 --- a/test/plugin/customParseFormat.test.js +++ b/test/plugin/customParseFormat.test.js @@ -2,6 +2,7 @@ import MockDate from 'mockdate' import moment from 'moment' import dayjs from '../../src' import customParseFormat from '../../src/plugin/customParseFormat' +import uk from '../../src/locale/uk' dayjs.extend(customParseFormat) @@ -84,3 +85,56 @@ it('fails with an invalid format', () => { expect(dayjs(input, format).format().toLowerCase()) .toBe(moment(input, format).format().toLowerCase()) }) + +it('parse month from string', () => { + const input = '2018 February 03' + const format = 'YYYY MMMM DD' + expect(dayjs(input, format).valueOf()).toBe(moment(input, format).valueOf()) +}) + +it('parse month from short string', () => { + const input = '2018 Feb 03' + const format = 'YYYY MMM DD' + expect(dayjs(input, format).valueOf()).toBe(moment(input, format).valueOf()) +}) + +it('parse month from string with locale in config', () => { + const input = '2018 лютий 03' + const format = 'YYYY MMMM DD' + + expect(dayjs(input, { format, locale: uk }).valueOf()).toBe(moment(input, format, 'uk').valueOf()) +}) + +it('parse month from short string with locale in config', () => { + const input = '2018 трав 03' + const format = 'YYYY MMM DD' + expect(dayjs(input, { format, locale: uk }).valueOf()).toBe(moment(input, format, 'uk').valueOf()) +}) + +it('return Invalid Date when parse corrupt string', () => { + const input = '2018 Turnip 03' + const format = 'YYYY MMMM DD' + expect(dayjs(input, format).format()).toBe('Invalid Date') +}) + +it('return Invalid Date when parse corrupt short string', () => { + const input = '2018 Dog 03' + const format = 'YYYY MMM DD' + expect(dayjs(input, format).format()).toBe('Invalid Date') +}) + +it('correctly parse month from string after changing locale globally', () => { + const input = '2018 лютий 03' + const format = 'YYYY MMMM DD' + + const dayjsLocale = dayjs().$locale() + const momentLocale = moment.locale() + try { + dayjs.locale(uk) + moment.locale('uk') + expect(dayjs(input, format).valueOf()).toBe(moment(input, format).valueOf()) + } finally { + dayjs.locale(dayjsLocale) + moment.locale(momentLocale) + } +}) From fe49db20791c5bfd84030a93d747ce46a73555a8 Mon Sep 17 00:00:00 2001 From: splashwizard Date: Sun, 24 Feb 2019 01:11:37 +0800 Subject: [PATCH 18/25] test: remove useless test --- test/manipulate.test.js | 4 ---- 1 file changed, 4 deletions(-) diff --git a/test/manipulate.test.js b/test/manipulate.test.js index c944027f..eb83f5d9 100644 --- a/test/manipulate.test.js +++ b/test/manipulate.test.js @@ -22,10 +22,6 @@ describe('StartOf EndOf', () => { }) }) - it('StartOf EndOf Week with week start setting', () => { - expect(dayjs().locale({ name: 'test', weekStart: 1 }).startOf('week').valueOf()).toBe(moment().startOf('week').add(1, 'day').valueOf()) - }) - it('StartOf EndOf Other -> no change', () => { expect(dayjs().startOf('otherString').valueOf()).toBe(moment().startOf('otherString').valueOf()) expect(dayjs().endOf('otherString').valueOf()).toBe(moment().endOf('otherString').valueOf()) From 2e5c9e5332c6481a4c98528c10b9dfce6c8bcdb3 Mon Sep 17 00:00:00 2001 From: splashwizard Date: Sun, 24 Feb 2019 01:16:16 +0800 Subject: [PATCH 19/25] docs: update customParseFormat docs --- docs/en/Plugin.md | 50 +++++++++++++++++++++-------------------- docs/es-es/Plugin.md | 53 +++++++++++++++++++++++--------------------- docs/ja/Plugin.md | 50 +++++++++++++++++++++-------------------- docs/ko/Plugin.md | 50 +++++++++++++++++++++-------------------- docs/pt-br/Plugin.md | 50 +++++++++++++++++++++-------------------- docs/zh-cn/Plugin.md | 50 +++++++++++++++++++++-------------------- 6 files changed, 158 insertions(+), 145 deletions(-) diff --git a/docs/en/Plugin.md b/docs/en/Plugin.md index ea00de43..0c70b7c7 100644 --- a/docs/en/Plugin.md +++ b/docs/en/Plugin.md @@ -261,35 +261,37 @@ dayjs.extend(customParseFormat) dayjs('05/02/69 1:02:03 PM -05:00', 'MM/DD/YY H:mm:ss A Z') // Returns an instance containing '1969-05-02T18:02:03.000Z' -dayjs('2018 Enero 15', { format: 'YYYY MMMM DD', locale: es }) +dayjs('2018 Enero 15', { format: 'YYYY MMMM DD', locale: 'es' }) // Returns an instance containing '2018-01-15T00:00:00.000Z' ``` #### List of all available format tokens -| Format | Output | Description | -| ------ | ------- | --------------------------------- | -| `YY` | 18 | Two-digit year | -| `YYYY` | 2018 | Four-digit year | -| `M` | 1-12 | Month, beginning at 1 | -| `MM` | 01-12 | Month, 2-digits | -| `D` | 1-31 | Day of month | -| `DD` | 01-31 | Day of month, 2-digits | -| `H` | 0-23 | Hours | -| `HH` | 00-23 | Hours, 2-digits | -| `h` | 1-12 | Hours, 12-hour clock | -| `hh` | 01-12 | Hours, 12-hour clock, 2-digits | -| `m` | 0-59 | Minutes | -| `mm` | 00-59 | Minutes, 2-digits | -| `s` | 0-59 | Seconds | -| `ss` | 00-59 | Seconds, 2-digits | -| `S` | 0-9 | Hundreds of milliseconds, 1-digit | -| `SS` | 00-99 | Tens of milliseconds, 2-digits | -| `SSS` | 000-999 | Milliseconds, 3-digits | -| `Z` | -5:00 | Offset from UTC | -| `ZZ` | -0500 | Compact offset from UTC, 2-digits | -| `A` | AM PM | Post or ante meridiem, upper-case | -| `a` | am pm | Post or ante meridiem, lower-case | +| Format | Output | Description | +| ------ | ---------------- | --------------------------------- | +| `YY` | 18 | Two-digit year | +| `YYYY` | 2018 | Four-digit year | +| `M` | 1-12 | Month, beginning at 1 | +| `MM` | 01-12 | Month, 2-digits | +| `MMM` | Jan-Dec | The abbreviated month name | +| `MMMM` | January-December | The full month name | +| `D` | 1-31 | Day of month | +| `DD` | 01-31 | Day of month, 2-digits | +| `H` | 0-23 | Hours | +| `HH` | 00-23 | Hours, 2-digits | +| `h` | 1-12 | Hours, 12-hour clock | +| `hh` | 01-12 | Hours, 12-hour clock, 2-digits | +| `m` | 0-59 | Minutes | +| `mm` | 00-59 | Minutes, 2-digits | +| `s` | 0-59 | Seconds | +| `ss` | 00-59 | Seconds, 2-digits | +| `S` | 0-9 | Hundreds of milliseconds, 1-digit | +| `SS` | 00-99 | Tens of milliseconds, 2-digits | +| `SSS` | 000-999 | Milliseconds, 3-digits | +| `Z` | -5:00 | Offset from UTC | +| `ZZ` | -0500 | Compact offset from UTC, 2-digits | +| `A` | AM PM | Post or ante meridiem, upper-case | +| `a` | am pm | Post or ante meridiem, lower-case | ## Customize diff --git a/docs/es-es/Plugin.md b/docs/es-es/Plugin.md index 5668155b..626d8118 100644 --- a/docs/es-es/Plugin.md +++ b/docs/es-es/Plugin.md @@ -248,7 +248,8 @@ dayjs('2010-04-01').quarter() // 2 ``` ### CustomParseFormat - - CustomParseFormat extends `dayjs()` constructor to support custom formats of input strings. + +- CustomParseFormat extends `dayjs()` constructor to support custom formats of input strings. To escape characters, wrap them in square brackets (e.g. `[G]`). Punctuation symbols (-:/.()) do not need to be wrapped. @@ -260,35 +261,37 @@ dayjs.extend(customParseFormat) dayjs('05/02/69 1:02:03 PM -05:00', 'MM/DD/YY H:mm:ss A Z') // Returns an instance containing '1969-05-02T18:02:03.000Z' -dayjs('2018 Enero 15', { format: 'YYYY MMMM DD', locale: es }) +dayjs('2018 Enero 15', { format: 'YYYY MMMM DD', locale: 'es' }) // Returns an instance containing '2018-01-15T00:00:00.000Z' ``` #### List of all available format tokens -| Format | Output | Description | -| ------ | ------- | --------------------------------- | -| `YY` | 18 | Two-digit year | -| `YYYY` | 2018 | Four-digit year | -| `M` | 1-12 | Month, beginning at 1 | -| `MM` | 01-12 | Month, 2-digits | -| `D` | 1-31 | Day of month | -| `DD` | 01-31 | Day of month, 2-digits | -| `H` | 0-23 | Hours | -| `HH` | 00-23 | Hours, 2-digits | -| `h` | 1-12 | Hours, 12-hour clock | -| `hh` | 01-12 | Hours, 12-hour clock, 2-digits | -| `m` | 0-59 | Minutes | -| `mm` | 00-59 | Minutes, 2-digits | -| `s` | 0-59 | Seconds | -| `ss` | 00-59 | Seconds, 2-digits | -| `S` | 0-9 | Hundreds of milliseconds, 1-digit | -| `SS` | 00-99 | Tens of milliseconds, 2-digits | -| `SSS` | 000-999 | Milliseconds, 3-digits | -| `Z` | -5:00 | Offset from UTC | -| `ZZ` | -0500 | Compact offset from UTC, 2-digits | -| `A` | AM PM | Post or ante meridiem, upper-case | -| `a` | am pm | Post or ante meridiem, lower-case | +| Format | Output | Description | +| ------ | ---------------- | --------------------------------- | +| `YY` | 18 | Two-digit year | +| `YYYY` | 2018 | Four-digit year | +| `M` | 1-12 | Month, beginning at 1 | +| `MM` | 01-12 | Month, 2-digits | +| `MMM` | Jan-Dec | The abbreviated month name | +| `MMMM` | January-December | The full month name | +| `D` | 1-31 | Day of month | +| `DD` | 01-31 | Day of month, 2-digits | +| `H` | 0-23 | Hours | +| `HH` | 00-23 | Hours, 2-digits | +| `h` | 1-12 | Hours, 12-hour clock | +| `hh` | 01-12 | Hours, 12-hour clock, 2-digits | +| `m` | 0-59 | Minutes | +| `mm` | 00-59 | Minutes, 2-digits | +| `s` | 0-59 | Seconds | +| `ss` | 00-59 | Seconds, 2-digits | +| `S` | 0-9 | Hundreds of milliseconds, 1-digit | +| `SS` | 00-99 | Tens of milliseconds, 2-digits | +| `SSS` | 000-999 | Milliseconds, 3-digits | +| `Z` | -5:00 | Offset from UTC | +| `ZZ` | -0500 | Compact offset from UTC, 2-digits | +| `A` | AM PM | Post or ante meridiem, upper-case | +| `a` | am pm | Post or ante meridiem, lower-case | ## Personalización diff --git a/docs/ja/Plugin.md b/docs/ja/Plugin.md index 981a29e2..c3a7ff65 100644 --- a/docs/ja/Plugin.md +++ b/docs/ja/Plugin.md @@ -270,35 +270,37 @@ dayjs.extend(customParseFormat) dayjs('05/02/69 1:02:03 PM -05:00', 'MM/DD/YY H:mm:ss A Z') // Returns an instance containing '1969-05-02T18:02:03.000Z' -dayjs('2018 5月 15', { format: 'YYYY MMMM DD', locale: ja }) +dayjs('2018 5月 15', { format: 'YYYY MMMM DD', locale: 'ja' }) // Returns an instance containing '2018-05-15T00:00:00.000Z' ``` #### List of all available format tokens -| Format | Output | Description | -| ------ | ------- | --------------------------------- | -| `YY` | 18 | Two-digit year | -| `YYYY` | 2018 | Four-digit year | -| `M` | 1-12 | Month, beginning at 1 | -| `MM` | 01-12 | Month, 2-digits | -| `D` | 1-31 | Day of month | -| `DD` | 01-31 | Day of month, 2-digits | -| `H` | 0-23 | Hours | -| `HH` | 00-23 | Hours, 2-digits | -| `h` | 1-12 | Hours, 12-hour clock | -| `hh` | 01-12 | Hours, 12-hour clock, 2-digits | -| `m` | 0-59 | Minutes | -| `mm` | 00-59 | Minutes, 2-digits | -| `s` | 0-59 | Seconds | -| `ss` | 00-59 | Seconds, 2-digits | -| `S` | 0-9 | Hundreds of milliseconds, 1-digit | -| `SS` | 00-99 | Tens of milliseconds, 2-digits | -| `SSS` | 000-999 | Milliseconds, 3-digits | -| `Z` | -5:00 | Offset from UTC | -| `ZZ` | -0500 | Compact offset from UTC, 2-digits | -| `A` | AM PM | Post or ante meridiem, upper-case | -| `a` | am pm | Post or ante meridiem, lower-case | +| Format | Output | Description | +| ------ | ---------------- | --------------------------------- | +| `YY` | 18 | Two-digit year | +| `YYYY` | 2018 | Four-digit year | +| `M` | 1-12 | Month, beginning at 1 | +| `MM` | 01-12 | Month, 2-digits | +| `MMM` | Jan-Dec | The abbreviated month name | +| `MMMM` | January-December | The full month name | +| `D` | 1-31 | Day of month | +| `DD` | 01-31 | Day of month, 2-digits | +| `H` | 0-23 | Hours | +| `HH` | 00-23 | Hours, 2-digits | +| `h` | 1-12 | Hours, 12-hour clock | +| `hh` | 01-12 | Hours, 12-hour clock, 2-digits | +| `m` | 0-59 | Minutes | +| `mm` | 00-59 | Minutes, 2-digits | +| `s` | 0-59 | Seconds | +| `ss` | 00-59 | Seconds, 2-digits | +| `S` | 0-9 | Hundreds of milliseconds, 1-digit | +| `SS` | 00-99 | Tens of milliseconds, 2-digits | +| `SSS` | 000-999 | Milliseconds, 3-digits | +| `Z` | -5:00 | Offset from UTC | +| `ZZ` | -0500 | Compact offset from UTC, 2-digits | +| `A` | AM PM | Post or ante meridiem, upper-case | +| `a` | am pm | Post or ante meridiem, lower-case | ## カスタマイズ diff --git a/docs/ko/Plugin.md b/docs/ko/Plugin.md index e203c811..3b894c0d 100644 --- a/docs/ko/Plugin.md +++ b/docs/ko/Plugin.md @@ -262,35 +262,37 @@ dayjs.extend(customParseFormat) dayjs('05/02/69 1:02:03 PM -05:00', 'MM/DD/YY H:mm:ss A Z') // Returns an instance containing '1969-05-02T18:02:03.000Z' -dayjs('2018 5월 15', { format: 'YYYY MMMM DD', locale: ko }) +dayjs('2018 5월 15', { format: 'YYYY MMMM DD', locale: 'ko' }) // Returns an instance containing '2018-05-15T00:00:00.000Z' ``` #### List of all available format tokens -| Format | Output | Description | -| ------ | ------- | --------------------------------- | -| `YY` | 18 | Two-digit year | -| `YYYY` | 2018 | Four-digit year | -| `M` | 1-12 | Month, beginning at 1 | -| `MM` | 01-12 | Month, 2-digits | -| `D` | 1-31 | Day of month | -| `DD` | 01-31 | Day of month, 2-digits | -| `H` | 0-23 | Hours | -| `HH` | 00-23 | Hours, 2-digits | -| `h` | 1-12 | Hours, 12-hour clock | -| `hh` | 01-12 | Hours, 12-hour clock, 2-digits | -| `m` | 0-59 | Minutes | -| `mm` | 00-59 | Minutes, 2-digits | -| `s` | 0-59 | Seconds | -| `ss` | 00-59 | Seconds, 2-digits | -| `S` | 0-9 | Hundreds of milliseconds, 1-digit | -| `SS` | 00-99 | Tens of milliseconds, 2-digits | -| `SSS` | 000-999 | Milliseconds, 3-digits | -| `Z` | -5:00 | Offset from UTC | -| `ZZ` | -0500 | Compact offset from UTC, 2-digits | -| `A` | AM PM | Post or ante meridiem, upper-case | -| `a` | am pm | Post or ante meridiem, lower-case | +| Format | Output | Description | +| ------ | ---------------- | --------------------------------- | +| `YY` | 18 | Two-digit year | +| `YYYY` | 2018 | Four-digit year | +| `M` | 1-12 | Month, beginning at 1 | +| `MM` | 01-12 | Month, 2-digits | +| `MMM` | Jan-Dec | The abbreviated month name | +| `MMMM` | January-December | The full month name | +| `D` | 1-31 | Day of month | +| `DD` | 01-31 | Day of month, 2-digits | +| `H` | 0-23 | Hours | +| `HH` | 00-23 | Hours, 2-digits | +| `h` | 1-12 | Hours, 12-hour clock | +| `hh` | 01-12 | Hours, 12-hour clock, 2-digits | +| `m` | 0-59 | Minutes | +| `mm` | 00-59 | Minutes, 2-digits | +| `s` | 0-59 | Seconds | +| `ss` | 00-59 | Seconds, 2-digits | +| `S` | 0-9 | Hundreds of milliseconds, 1-digit | +| `SS` | 00-99 | Tens of milliseconds, 2-digits | +| `SSS` | 000-999 | Milliseconds, 3-digits | +| `Z` | -5:00 | Offset from UTC | +| `ZZ` | -0500 | Compact offset from UTC, 2-digits | +| `A` | AM PM | Post or ante meridiem, upper-case | +| `a` | am pm | Post or ante meridiem, lower-case | ## Customize diff --git a/docs/pt-br/Plugin.md b/docs/pt-br/Plugin.md index 04581f34..df125801 100644 --- a/docs/pt-br/Plugin.md +++ b/docs/pt-br/Plugin.md @@ -261,35 +261,37 @@ dayjs.extend(customParseFormat) dayjs('05/02/69 1:02:03 PM -05:00', 'MM/DD/YY H:mm:ss A Z') // Returns an instance containing '1969-05-02T18:02:03.000Z' -dayjs('2018 Fevereiro 15', { format: 'YYYY MMMM DD', locale: pt_br }) +dayjs('2018 Fevereiro 15', { format: 'YYYY MMMM DD', locale: 'pt_br' }) // Returns an instance containing '2018-02-15T00:00:00.000Z' ``` #### List of all available format tokens -| Format | Output | Description | -| ------ | ------- | --------------------------------- | -| `YY` | 18 | Two-digit year | -| `YYYY` | 2018 | Four-digit year | -| `M` | 1-12 | Month, beginning at 1 | -| `MM` | 01-12 | Month, 2-digits | -| `D` | 1-31 | Day of month | -| `DD` | 01-31 | Day of month, 2-digits | -| `H` | 0-23 | Hours | -| `HH` | 00-23 | Hours, 2-digits | -| `h` | 1-12 | Hours, 12-hour clock | -| `hh` | 01-12 | Hours, 12-hour clock, 2-digits | -| `m` | 0-59 | Minutes | -| `mm` | 00-59 | Minutes, 2-digits | -| `s` | 0-59 | Seconds | -| `ss` | 00-59 | Seconds, 2-digits | -| `S` | 0-9 | Hundreds of milliseconds, 1-digit | -| `SS` | 00-99 | Tens of milliseconds, 2-digits | -| `SSS` | 000-999 | Milliseconds, 3-digits | -| `Z` | -5:00 | Offset from UTC | -| `ZZ` | -0500 | Compact offset from UTC, 2-digits | -| `A` | AM PM | Post or ante meridiem, upper-case | -| `a` | am pm | Post or ante meridiem, lower-case | +| Format | Output | Description | +| ------ | ---------------- | --------------------------------- | +| `YY` | 18 | Two-digit year | +| `YYYY` | 2018 | Four-digit year | +| `M` | 1-12 | Month, beginning at 1 | +| `MM` | 01-12 | Month, 2-digits | +| `MMM` | Jan-Dec | The abbreviated month name | +| `MMMM` | January-December | The full month name | +| `D` | 1-31 | Day of month | +| `DD` | 01-31 | Day of month, 2-digits | +| `H` | 0-23 | Hours | +| `HH` | 00-23 | Hours, 2-digits | +| `h` | 1-12 | Hours, 12-hour clock | +| `hh` | 01-12 | Hours, 12-hour clock, 2-digits | +| `m` | 0-59 | Minutes | +| `mm` | 00-59 | Minutes, 2-digits | +| `s` | 0-59 | Seconds | +| `ss` | 00-59 | Seconds, 2-digits | +| `S` | 0-9 | Hundreds of milliseconds, 1-digit | +| `SS` | 00-99 | Tens of milliseconds, 2-digits | +| `SSS` | 000-999 | Milliseconds, 3-digits | +| `Z` | -5:00 | Offset from UTC | +| `ZZ` | -0500 | Compact offset from UTC, 2-digits | +| `A` | AM PM | Post or ante meridiem, upper-case | +| `a` | am pm | Post or ante meridiem, lower-case | ## Customizar diff --git a/docs/zh-cn/Plugin.md b/docs/zh-cn/Plugin.md index 02938ab3..407ef92b 100644 --- a/docs/zh-cn/Plugin.md +++ b/docs/zh-cn/Plugin.md @@ -261,35 +261,37 @@ dayjs.extend(customParseFormat) dayjs('05/02/69 1:02:03 PM -05:00', 'MM/DD/YY H:mm:ss A Z') // Returns an instance containing '1969-05-02T18:02:03.000Z' -dayjs('2018 五月 15', { format: 'YYYY MMMM DD', locale: zh_cn }) +dayjs('2018 五月 15', { format: 'YYYY MMMM DD', locale: 'zh_cn' }) // Returns an instance containing '2018-05-15T00:00:00.000Z' ``` #### List of all available format tokens -| Format | Output | Description | -| ------ | ------- | --------------------------------- | -| `YY` | 18 | Two-digit year | -| `YYYY` | 2018 | Four-digit year | -| `M` | 1-12 | Month, beginning at 1 | -| `MM` | 01-12 | Month, 2-digits | -| `D` | 1-31 | Day of month | -| `DD` | 01-31 | Day of month, 2-digits | -| `H` | 0-23 | Hours | -| `HH` | 00-23 | Hours, 2-digits | -| `h` | 1-12 | Hours, 12-hour clock | -| `hh` | 01-12 | Hours, 12-hour clock, 2-digits | -| `m` | 0-59 | Minutes | -| `mm` | 00-59 | Minutes, 2-digits | -| `s` | 0-59 | Seconds | -| `ss` | 00-59 | Seconds, 2-digits | -| `S` | 0-9 | Hundreds of milliseconds, 1-digit | -| `SS` | 00-99 | Tens of milliseconds, 2-digits | -| `SSS` | 000-999 | Milliseconds, 3-digits | -| `Z` | -5:00 | Offset from UTC | -| `ZZ` | -0500 | Compact offset from UTC, 2-digits | -| `A` | AM PM | Post or ante meridiem, upper-case | -| `a` | am pm | Post or ante meridiem, lower-case | +| Format | Output | Description | +| ------ | ---------------- | --------------------------------- | +| `YY` | 18 | Two-digit year | +| `YYYY` | 2018 | Four-digit year | +| `M` | 1-12 | Month, beginning at 1 | +| `MM` | 01-12 | Month, 2-digits | +| `MMM` | Jan-Dec | The abbreviated month name | +| `MMMM` | January-December | The full month name | +| `D` | 1-31 | Day of month | +| `DD` | 01-31 | Day of month, 2-digits | +| `H` | 0-23 | Hours | +| `HH` | 00-23 | Hours, 2-digits | +| `h` | 1-12 | Hours, 12-hour clock | +| `hh` | 01-12 | Hours, 12-hour clock, 2-digits | +| `m` | 0-59 | Minutes | +| `mm` | 00-59 | Minutes, 2-digits | +| `s` | 0-59 | Seconds | +| `ss` | 00-59 | Seconds, 2-digits | +| `S` | 0-9 | Hundreds of milliseconds, 1-digit | +| `SS` | 00-99 | Tens of milliseconds, 2-digits | +| `SSS` | 000-999 | Milliseconds, 3-digits | +| `Z` | -5:00 | Offset from UTC | +| `ZZ` | -0500 | Compact offset from UTC, 2-digits | +| `A` | AM PM | Post or ante meridiem, upper-case | +| `a` | am pm | Post or ante meridiem, lower-case | ## 自定义 From 622382fd74c6baa9e756a85d9516b979c19d76f6 Mon Sep 17 00:00:00 2001 From: splashwizard Date: Sun, 24 Feb 2019 02:17:26 +0800 Subject: [PATCH 20/25] refactor: update customParseFormat, allow parse locale from argument --- src/index.js | 5 +++-- src/plugin/customParseFormat/index.js | 6 +++--- test/plugin/customParseFormat.test.js | 13 +++++++++++++ 3 files changed, 19 insertions(+), 5 deletions(-) diff --git a/src/index.js b/src/index.js index e33a80a0..e9f6f1aa 100644 --- a/src/index.js +++ b/src/index.js @@ -28,12 +28,12 @@ const parseLocale = (preset, object, isLocal) => { return l } -const dayjs = (date, c) => { +const dayjs = (date, c, pl) => { if (isDayjs(date)) { return date.clone() } // eslint-disable-next-line no-nested-ternary - const cfg = c ? (typeof c === 'string' ? { format: c } : c) : {} + const cfg = c ? (typeof c === 'string' ? { format: c, pl } : c) : {} cfg.date = date return new Dayjs(cfg) // eslint-disable-line no-use-before-define } @@ -408,5 +408,6 @@ dayjs.unix = timestamp => ( ) dayjs.en = Ls[L] +dayjs.Ls = Ls export default dayjs diff --git a/src/plugin/customParseFormat/index.js b/src/plugin/customParseFormat/index.js index 0d8e0acb..3755b34c 100644 --- a/src/plugin/customParseFormat/index.js +++ b/src/plugin/customParseFormat/index.js @@ -159,13 +159,13 @@ const parseFormattedInput = (input, format) => { } -export default (o, C) => { +export default (o, C, d) => { const proto = C.prototype const oldParse = proto.parse proto.parse = function (cfg) { - const { date: input, format } = cfg + const { date: input, format, pl } = cfg if (format) { - locale = this.$locale() + locale = pl ? d.Ls[pl] : this.$locale() this.$d = parseFormattedInput(input, format) this.init(cfg) } else { diff --git a/test/plugin/customParseFormat.test.js b/test/plugin/customParseFormat.test.js index b278462f..1b2bef21 100644 --- a/test/plugin/customParseFormat.test.js +++ b/test/plugin/customParseFormat.test.js @@ -111,6 +111,19 @@ it('parse month from short string with locale in config', () => { expect(dayjs(input, { format, locale: uk }).valueOf()).toBe(moment(input, format, 'uk').valueOf()) }) +it('parse month from short string with locale in argument', () => { + const input = '2018 трав 03' + const format = 'YYYY MMM DD' + expect(dayjs(input, format, 'uk').valueOf()).toBe(moment(input, format, 'uk').valueOf()) +}) + +it('parse month from string with locale in argument', () => { + const input = '2018 лютий 03' + const format = 'YYYY MMMM DD' + + expect(dayjs(input, format, 'uk').valueOf()).toBe(moment(input, format, 'uk').valueOf()) +}) + it('return Invalid Date when parse corrupt string', () => { const input = '2018 Turnip 03' const format = 'YYYY MMMM DD' From 68b4cd3170554559cee3c1e37c195b59fb6af03d Mon Sep 17 00:00:00 2001 From: splashwizard Date: Sun, 24 Feb 2019 02:21:38 +0800 Subject: [PATCH 21/25] docs: update docs customParseFormat --- docs/en/Plugin.md | 2 +- docs/es-es/Plugin.md | 2 +- docs/ja/Plugin.md | 2 +- docs/ko/Plugin.md | 2 +- docs/pt-br/Plugin.md | 2 +- docs/zh-cn/Plugin.md | 2 +- types/index.d.ts | 2 +- 7 files changed, 7 insertions(+), 7 deletions(-) diff --git a/docs/en/Plugin.md b/docs/en/Plugin.md index 0c70b7c7..313f2d90 100644 --- a/docs/en/Plugin.md +++ b/docs/en/Plugin.md @@ -261,7 +261,7 @@ dayjs.extend(customParseFormat) dayjs('05/02/69 1:02:03 PM -05:00', 'MM/DD/YY H:mm:ss A Z') // Returns an instance containing '1969-05-02T18:02:03.000Z' -dayjs('2018 Enero 15', { format: 'YYYY MMMM DD', locale: 'es' }) +dayjs('2018 Enero 15', 'YYYY MMMM DD', 'es') // Returns an instance containing '2018-01-15T00:00:00.000Z' ``` diff --git a/docs/es-es/Plugin.md b/docs/es-es/Plugin.md index 626d8118..d786eeec 100644 --- a/docs/es-es/Plugin.md +++ b/docs/es-es/Plugin.md @@ -261,7 +261,7 @@ dayjs.extend(customParseFormat) dayjs('05/02/69 1:02:03 PM -05:00', 'MM/DD/YY H:mm:ss A Z') // Returns an instance containing '1969-05-02T18:02:03.000Z' -dayjs('2018 Enero 15', { format: 'YYYY MMMM DD', locale: 'es' }) +dayjs('2018 Enero 15', 'YYYY MMMM DD', 'es') // Returns an instance containing '2018-01-15T00:00:00.000Z' ``` diff --git a/docs/ja/Plugin.md b/docs/ja/Plugin.md index c3a7ff65..8aed2916 100644 --- a/docs/ja/Plugin.md +++ b/docs/ja/Plugin.md @@ -270,7 +270,7 @@ dayjs.extend(customParseFormat) dayjs('05/02/69 1:02:03 PM -05:00', 'MM/DD/YY H:mm:ss A Z') // Returns an instance containing '1969-05-02T18:02:03.000Z' -dayjs('2018 5月 15', { format: 'YYYY MMMM DD', locale: 'ja' }) +dayjs('2018 5月 15', 'YYYY MMMM DD', 'ja') // Returns an instance containing '2018-05-15T00:00:00.000Z' ``` diff --git a/docs/ko/Plugin.md b/docs/ko/Plugin.md index 3b894c0d..ce1447e8 100644 --- a/docs/ko/Plugin.md +++ b/docs/ko/Plugin.md @@ -262,7 +262,7 @@ dayjs.extend(customParseFormat) dayjs('05/02/69 1:02:03 PM -05:00', 'MM/DD/YY H:mm:ss A Z') // Returns an instance containing '1969-05-02T18:02:03.000Z' -dayjs('2018 5월 15', { format: 'YYYY MMMM DD', locale: 'ko' }) +dayjs('2018 5월 15', 'YYYY MMMM DD', 'ko') // Returns an instance containing '2018-05-15T00:00:00.000Z' ``` diff --git a/docs/pt-br/Plugin.md b/docs/pt-br/Plugin.md index df125801..e0705169 100644 --- a/docs/pt-br/Plugin.md +++ b/docs/pt-br/Plugin.md @@ -261,7 +261,7 @@ dayjs.extend(customParseFormat) dayjs('05/02/69 1:02:03 PM -05:00', 'MM/DD/YY H:mm:ss A Z') // Returns an instance containing '1969-05-02T18:02:03.000Z' -dayjs('2018 Fevereiro 15', { format: 'YYYY MMMM DD', locale: 'pt_br' }) +dayjs('2018 Fevereiro 15', 'YYYY MMMM DD', 'pt_br') // Returns an instance containing '2018-02-15T00:00:00.000Z' ``` diff --git a/docs/zh-cn/Plugin.md b/docs/zh-cn/Plugin.md index 407ef92b..3c930026 100644 --- a/docs/zh-cn/Plugin.md +++ b/docs/zh-cn/Plugin.md @@ -261,7 +261,7 @@ dayjs.extend(customParseFormat) dayjs('05/02/69 1:02:03 PM -05:00', 'MM/DD/YY H:mm:ss A Z') // Returns an instance containing '1969-05-02T18:02:03.000Z' -dayjs('2018 五月 15', { format: 'YYYY MMMM DD', locale: 'zh_cn' }) +dayjs('2018 五月 15', 'YYYY MMMM DD', 'zh_cn') // Returns an instance containing '2018-05-15T00:00:00.000Z' ``` diff --git a/types/index.d.ts b/types/index.d.ts index 24ac01f1..c1db5910 100644 --- a/types/index.d.ts +++ b/types/index.d.ts @@ -1,5 +1,5 @@ export = dayjs; -declare function dayjs (date?: dayjs.ConfigType, option?: dayjs.OptionType): dayjs.Dayjs +declare function dayjs (date?: dayjs.ConfigType, option?: dayjs.OptionType, locale?: string): dayjs.Dayjs declare namespace dayjs { export type ConfigType = string | number | Date | Dayjs From c00815ceb5880d107936cc4e3d6517a24065bc4b Mon Sep 17 00:00:00 2001 From: splashwizard Date: Sun, 24 Feb 2019 03:09:04 +0800 Subject: [PATCH 22/25] build: update locale import path in esm fix #501 --- build/esm.js | 21 +++++++++++++++++++++ package.json | 2 +- 2 files changed, 22 insertions(+), 1 deletion(-) create mode 100644 build/esm.js diff --git a/build/esm.js b/build/esm.js new file mode 100644 index 00000000..634f3aea --- /dev/null +++ b/build/esm.js @@ -0,0 +1,21 @@ +const fs = require('fs') +const path = require('path') +const util = require('util') + +const { promisify } = util + +const localeDir = path.join(process.env.PWD, 'esm/locale'); + +(async () => { + try { + const readLocaleDir = await promisify(fs.readdir)(localeDir) + readLocaleDir.forEach(async (l) => { + const filePath = path.join(localeDir, l) + const readFile = await promisify(fs.readFile)(filePath, 'utf8') + const result = readFile.replace("'dayjs'", "'../index'") + await promisify(fs.writeFile)(filePath, result, 'utf8') + }) + } catch (e) { + console.error(e) + } +})() diff --git a/package.json b/package.json index e7f2af7a..a8a68264 100644 --- a/package.json +++ b/package.json @@ -10,7 +10,7 @@ "test-tz": "jest test/timezone.test --coverage=false", "lint": "./node_modules/.bin/eslint src/* test/* build/*", "prettier": "prettier --write \"docs/**/*.md\"", - "babel": "cross-env BABEL_ENV=build babel src --out-dir esm --copy-files", + "babel": "cross-env BABEL_ENV=build babel src --out-dir esm --copy-files && node build/esm", "build": "cross-env BABEL_ENV=build node build && npm run size", "sauce": "npx karma start karma.sauce.conf.js", "test:sauce": "npm run sauce -- 0 && npm run sauce -- 1 && npm run sauce -- 2 && npm run sauce -- 3", From 99e4c1c73488f2a3659d101ceb0305b7ec4c9662 Mon Sep 17 00:00:00 2001 From: obiwycliffe <33378361+0biWycliffe@users.noreply.github.com> Date: Sun, 24 Feb 2019 12:43:39 +0300 Subject: [PATCH 23/25] fix: Add Swahili locale (#508) --- src/locale/sw.js | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 src/locale/sw.js diff --git a/src/locale/sw.js b/src/locale/sw.js new file mode 100644 index 00000000..b0534a62 --- /dev/null +++ b/src/locale/sw.js @@ -0,0 +1,36 @@ +import dayjs from 'dayjs' + +const locale = { + name: 'sw', + weekdays: 'Jumapili_Jumatatu_Jumanne_Jumatano_Alhamisi_Ijuma_Jumamosi'.split('_'), + months: 'Januari_Februari_Machi_Aprili_Mei_Juni_Julai_Agosti_Septemba_Octoba_Novemba_Disemba'.split('_'), + weekStart: 1, + 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' + }, + relativeTime: { + future: 'Ujao %s', + past: 'Uliopita %s', + s: 'sekunde', + m: 'dakika', + mm: '%d madakika', + h: 'saa', + hh: '%d masaa', + d: 'siku', + dd: '%d masiku', + M: 'mwezi', + MM: '%d miezi', + y: 'mwaka', + yy: '%d miaka' + } +} + +dayjs.locale(locale, null, true) + +export default locale From 7d5c776a20b0dd0d741fd8eda2a2e1bc4758071f Mon Sep 17 00:00:00 2001 From: Tracy Terry <33895167+Tracyterry@users.noreply.github.com> Date: Sun, 24 Feb 2019 12:43:57 +0300 Subject: [PATCH 24/25] chore: swahili version (#509) --- src/locale/swa.js | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 src/locale/swa.js diff --git a/src/locale/swa.js b/src/locale/swa.js new file mode 100644 index 00000000..bd306bad --- /dev/null +++ b/src/locale/swa.js @@ -0,0 +1,39 @@ +import dayjs from 'dayjs' + +const locale = { + name: 'swa', + weekdays: 'Jumapili_Jumatatu_Jumanne_Jumatano_Alhamisi_Ijumaa_Jumamosi'.split('_'), + weekdaysShort: 'Jumapili_Jumatatu_Jumanne_Jumatano_Alhamisi_Ijumaa_Jumamosi'.split('_'), + weekdaysMin: 'S_M_T_W_T_F_S'.split('_'), + months: 'Januari_Februari_Machi_Aprili_Mei_Juni_Julai_Agosti_Septemba_Oktoba_Novemba_Desemba'.split('_'), + monthsShort: 'Jan_Feb_Mac_Apr_Mei_Jun_Jul_Ago_Sep_Okt_Nov_Des'.split('_'), + weekStart: 1, + ordinal: n => n, + relativeTime: { + future: 'kwa %s', + past: '%s iliyopita', + s: 'sekunde', + m: 'dakika', + mm: '%d dakika', + h: 'saa', + hh: '%d masaa', + d: 'siku', + dd: '%d masiku', + M: 'mwezi', + MM: '%d miezi', + y: 'mwaka', + yy: '%d miaka' + }, + formats: { + LT: 'HH:mm', + LTS: 'HH:mm:ss', + L: 'DD/MM/YYYY', + LL: 'D MMMM YYYY', + LLL: 'D MMMM YYYY HH:mm', + LLLL: 'dddd, D MMMM YYYY HH:mm' + } +} + +dayjs.locale(locale, null, true) + +export default locale From 4bfbced75c9e21b99d2fae0bd7d4c9d3afacea4f Mon Sep 17 00:00:00 2001 From: splashwizard Date: Sun, 24 Feb 2019 17:49:44 +0800 Subject: [PATCH 25/25] chore: update sw locale --- build/esm.js | 2 +- src/locale/sw.js | 49 +++++++++++++++++++++++++---------------------- src/locale/swa.js | 39 ------------------------------------- 3 files changed, 27 insertions(+), 63 deletions(-) delete mode 100644 src/locale/swa.js diff --git a/build/esm.js b/build/esm.js index 634f3aea..92f2dfde 100644 --- a/build/esm.js +++ b/build/esm.js @@ -16,6 +16,6 @@ const localeDir = path.join(process.env.PWD, 'esm/locale'); await promisify(fs.writeFile)(filePath, result, 'utf8') }) } catch (e) { - console.error(e) + console.error(e) // eslint-disable-line no-console } })() diff --git a/src/locale/sw.js b/src/locale/sw.js index b0534a62..7e68f481 100644 --- a/src/locale/sw.js +++ b/src/locale/sw.js @@ -2,32 +2,35 @@ import dayjs from 'dayjs' const locale = { name: 'sw', - weekdays: 'Jumapili_Jumatatu_Jumanne_Jumatano_Alhamisi_Ijuma_Jumamosi'.split('_'), - months: 'Januari_Februari_Machi_Aprili_Mei_Juni_Julai_Agosti_Septemba_Octoba_Novemba_Disemba'.split('_'), + weekdays: 'Jumapili_Jumatatu_Jumanne_Jumatano_Alhamisi_Ijumaa_Jumamosi'.split('_'), + weekdaysShort: 'Jpl_Jtat_Jnne_Jtan_Alh_Ijm_Jmos'.split('_'), + weekdaysMin: 'J2_J3_J4_J5_Al_Ij_J1'.split('_'), + months: 'Januari_Februari_Machi_Aprili_Mei_Juni_Julai_Agosti_Septemba_Oktoba_Novemba_Desemba'.split('_'), + monthsShort: 'Jan_Feb_Mac_Apr_Mei_Jun_Jul_Ago_Sep_Okt_Nov_Des'.split('_'), weekStart: 1, - ordinal: n => `${n}.`, + ordinal: n => n, + relativeTime: { + future: '%s baadaye', + past: 'tokea %s', + s: 'hivi punde', + m: 'dakika moja', + mm: 'dakika %d', + h: 'saa limoja', + hh: 'masaa %d', + d: 'siku moja', + dd: 'masiku %d', + M: 'mwezi mmoja', + MM: 'miezi %d', + y: 'mwaka mmoja', + yy: 'miaka %d' + }, formats: { - LT: 'H:mm', - LTS: 'H:mm:ss', + LT: 'HH:mm', + LTS: 'HH:mm:ss', L: 'DD.MM.YYYY', - LL: 'D. MMMM YYYY', - LLL: 'D. MMMM YYYY H:mm', - LLLL: 'dddd D. MMMM YYYY H:mm' - }, - relativeTime: { - future: 'Ujao %s', - past: 'Uliopita %s', - s: 'sekunde', - m: 'dakika', - mm: '%d madakika', - h: 'saa', - hh: '%d masaa', - d: 'siku', - dd: '%d masiku', - M: 'mwezi', - MM: '%d miezi', - y: 'mwaka', - yy: '%d miaka' + LL: 'D MMMM YYYY', + LLL: 'D MMMM YYYY HH:mm', + LLLL: 'dddd, D MMMM YYYY HH:mm' } } diff --git a/src/locale/swa.js b/src/locale/swa.js deleted file mode 100644 index bd306bad..00000000 --- a/src/locale/swa.js +++ /dev/null @@ -1,39 +0,0 @@ -import dayjs from 'dayjs' - -const locale = { - name: 'swa', - weekdays: 'Jumapili_Jumatatu_Jumanne_Jumatano_Alhamisi_Ijumaa_Jumamosi'.split('_'), - weekdaysShort: 'Jumapili_Jumatatu_Jumanne_Jumatano_Alhamisi_Ijumaa_Jumamosi'.split('_'), - weekdaysMin: 'S_M_T_W_T_F_S'.split('_'), - months: 'Januari_Februari_Machi_Aprili_Mei_Juni_Julai_Agosti_Septemba_Oktoba_Novemba_Desemba'.split('_'), - monthsShort: 'Jan_Feb_Mac_Apr_Mei_Jun_Jul_Ago_Sep_Okt_Nov_Des'.split('_'), - weekStart: 1, - ordinal: n => n, - relativeTime: { - future: 'kwa %s', - past: '%s iliyopita', - s: 'sekunde', - m: 'dakika', - mm: '%d dakika', - h: 'saa', - hh: '%d masaa', - d: 'siku', - dd: '%d masiku', - M: 'mwezi', - MM: '%d miezi', - y: 'mwaka', - yy: '%d miaka' - }, - formats: { - LT: 'HH:mm', - LTS: 'HH:mm:ss', - L: 'DD/MM/YYYY', - LL: 'D MMMM YYYY', - LLL: 'D MMMM YYYY HH:mm', - LLLL: 'dddd, D MMMM YYYY HH:mm' - } -} - -dayjs.locale(locale, null, true) - -export default locale