From 8d63d885fdd72b51bfdf01cbd6f45c773f71363a Mon Sep 17 00:00:00 2001 From: iamkun Date: Thu, 7 Mar 2019 13:16:14 +0800 Subject: [PATCH 01/22] fix: API .locale() with no argument should return current locale name string --- src/index.js | 1 + test/locale.test.js | 12 ++++++++++++ types/index.d.ts | 2 ++ 3 files changed, 15 insertions(+) diff --git a/src/index.js b/src/index.js index 4f96f9c91..413b5becc 100644 --- a/src/index.js +++ b/src/index.js @@ -346,6 +346,7 @@ class Dayjs { } locale(preset, object) { + if (!preset) return this.$L const that = this.clone() that.$L = parseLocale(preset, object, true) return that diff --git a/test/locale.test.js b/test/locale.test.js index 06560b6ba..8438bd095 100644 --- a/test/locale.test.js +++ b/test/locale.test.js @@ -1,4 +1,5 @@ import MockDate from 'mockdate' +import moment from 'moment' import dayjs from '../src' import es from '../src/locale/es' @@ -44,6 +45,17 @@ it('set global locale', () => { .toBe('Saturday 28, April') }) +it('get instance locale name', () => { + expect(dayjs().locale()).toBe('en') + expect(dayjs().locale()).toBe(moment().locale()) + expect(dayjs().locale('es').locale()).toBe('es') + expect(dayjs().locale('es').locale()).toBe(moment().locale('es').locale()) + dayjs.locale(es) + moment.locale('es') + expect(dayjs().locale()).toBe('es') + expect(dayjs().locale()).toBe(moment().locale()) +}) + it('immutable instance locale', () => { dayjs.locale('en') const origin = dayjs('2018-4-28') diff --git a/types/index.d.ts b/types/index.d.ts index 22ea11726..d6f547d22 100644 --- a/types/index.d.ts +++ b/types/index.d.ts @@ -85,6 +85,8 @@ declare namespace dayjs { isAfter(date: ConfigType, unit?: OpUnitType): boolean + locale(): string + locale(preset: string | { name: string, [key: string]: any }, object?: { [key: string]: any }): Dayjs } From 40a3431d922a1956dc4bc20a09aa4a1a9990b8e8 Mon Sep 17 00:00:00 2001 From: iamkun Date: Thu, 7 Mar 2019 13:21:56 +0800 Subject: [PATCH 02/22] fix: Move toObject, toArray API to separate plugin from core --- src/index.js | 24 ------------------------ src/plugin/toArray/index.js | 15 +++++++++++++++ src/plugin/toObject/index.js | 15 +++++++++++++++ types/index.d.ts | 14 -------------- types/plugin/toArray.d.ts | 10 ++++++++++ types/plugin/toObject.d.ts | 20 ++++++++++++++++++++ 6 files changed, 60 insertions(+), 38 deletions(-) create mode 100644 src/plugin/toArray/index.js create mode 100644 src/plugin/toObject/index.js create mode 100644 types/plugin/toArray.d.ts create mode 100644 types/plugin/toObject.d.ts diff --git a/src/index.js b/src/index.js index 413b5becc..55e5d647f 100644 --- a/src/index.js +++ b/src/index.js @@ -360,18 +360,6 @@ class Dayjs { return new Date(this.$d) } - toArray() { - return [ - this.$y, - this.$M, - this.$D, - this.$H, - this.$m, - this.$s, - this.$ms - ] - } - toJSON() { return this.toISOString() } @@ -383,18 +371,6 @@ class Dayjs { return this.$d.toISOString() } - toObject() { - return { - years: this.$y, - months: this.$M, - date: this.$D, - hours: this.$H, - minutes: this.$m, - seconds: this.$s, - milliseconds: this.$ms - } - } - toString() { return this.$d.toUTCString() } diff --git a/src/plugin/toArray/index.js b/src/plugin/toArray/index.js new file mode 100644 index 000000000..9ffc16040 --- /dev/null +++ b/src/plugin/toArray/index.js @@ -0,0 +1,15 @@ +export default (o, c) => { + const proto = c.prototype + proto.toArray = function () { + return [ + this.$y, + this.$M, + this.$D, + this.$H, + this.$m, + this.$s, + this.$ms + ] + } +} + diff --git a/src/plugin/toObject/index.js b/src/plugin/toObject/index.js new file mode 100644 index 000000000..08d22d844 --- /dev/null +++ b/src/plugin/toObject/index.js @@ -0,0 +1,15 @@ +export default (o, c) => { + const proto = c.prototype + proto.toObject = function () { + return { + years: this.$y, + months: this.$M, + date: this.$D, + hours: this.$H, + minutes: this.$m, + seconds: this.$s, + milliseconds: this.$ms + } + } +} + diff --git a/types/index.d.ts b/types/index.d.ts index d6f547d22..abadb4692 100644 --- a/types/index.d.ts +++ b/types/index.d.ts @@ -12,16 +12,6 @@ declare namespace dayjs { type OpUnitTypeShort = 'w' export type OpUnitType = UnitType | "week" | OpUnitTypeShort; - interface DayjsObject { - years: number - months: number - date: number - hours: number - minutes: number - seconds: number - milliseconds: number - } - class Dayjs { constructor (config?: ConfigType) @@ -67,14 +57,10 @@ declare namespace dayjs { toDate(): Date - toArray(): number[] - toJSON(): string toISOString(): string - toObject(): DayjsObject - toString(): string utcOffset(): number diff --git a/types/plugin/toArray.d.ts b/types/plugin/toArray.d.ts new file mode 100644 index 000000000..45f1f0c3c --- /dev/null +++ b/types/plugin/toArray.d.ts @@ -0,0 +1,10 @@ +import { PluginFunc } from 'dayjs' + +declare const plugin: PluginFunc +export = plugin + +declare module 'dayjs' { + interface Dayjs { + toArray(): number[] + } +} diff --git a/types/plugin/toObject.d.ts b/types/plugin/toObject.d.ts new file mode 100644 index 000000000..ca12aaf00 --- /dev/null +++ b/types/plugin/toObject.d.ts @@ -0,0 +1,20 @@ +import { PluginFunc } from 'dayjs' + +declare const plugin: PluginFunc +export = plugin + +interface DayjsObject { + years: number + months: number + date: number + hours: number + minutes: number + seconds: number + milliseconds: number +} + +declare module 'dayjs' { + interface Dayjs { + toObject(): DayjsObject + } +} From 5135f2da008b9a8362d4ad4c3e0d5c1ade708ad8 Mon Sep 17 00:00:00 2001 From: iamkun Date: Thu, 7 Mar 2019 13:24:24 +0800 Subject: [PATCH 03/22] test: Move toArray toObject test --- test/display.test.js | 8 -------- test/plugin/toArray.test.js | 18 ++++++++++++++++++ test/plugin/toObject.test.js | 18 ++++++++++++++++++ 3 files changed, 36 insertions(+), 8 deletions(-) create mode 100644 test/plugin/toArray.test.js create mode 100644 test/plugin/toObject.test.js diff --git a/test/display.test.js b/test/display.test.js index a8a328688..603a6988b 100644 --- a/test/display.test.js +++ b/test/display.test.js @@ -230,10 +230,6 @@ it('As Javascript Date -> toDate', () => { expect(jsDate.toUTCString()).not.toBe(base.toString()) }) -it('As Array -> toArray', () => { - expect(dayjs().toArray()).toEqual(moment().toArray()) -}) - it('As JSON -> toJSON', () => { expect(dayjs().toJSON()).toBe(moment().toJSON()) }) @@ -241,7 +237,3 @@ it('As JSON -> toJSON', () => { it('As ISO 8601 String -> toISOString e.g. 2013-02-04T22:44:30.652Z', () => { expect(dayjs().toISOString()).toBe(moment().toISOString()) }) - -it('As Object -> toObject', () => { - expect(dayjs().toObject()).toEqual(moment().toObject()) -}) diff --git a/test/plugin/toArray.test.js b/test/plugin/toArray.test.js new file mode 100644 index 000000000..674c76f97 --- /dev/null +++ b/test/plugin/toArray.test.js @@ -0,0 +1,18 @@ +import MockDate from 'mockdate' +import moment from 'moment' +import dayjs from '../../src' +import toArray from '../../src/plugin/toArray' + +dayjs.extend(toArray) + +beforeEach(() => { + MockDate.set(new Date()) +}) + +afterEach(() => { + MockDate.reset() +}) + +it('As Array -> toArray', () => { + expect(dayjs().toArray()).toEqual(moment().toArray()) +}) diff --git a/test/plugin/toObject.test.js b/test/plugin/toObject.test.js new file mode 100644 index 000000000..3d0c21335 --- /dev/null +++ b/test/plugin/toObject.test.js @@ -0,0 +1,18 @@ +import MockDate from 'mockdate' +import moment from 'moment' +import dayjs from '../../src' +import toObject from '../../src/plugin/toObject' + +dayjs.extend(toObject) + +beforeEach(() => { + MockDate.set(new Date()) +}) + +afterEach(() => { + MockDate.reset() +}) + +it('As Object -> toObject', () => { + expect(dayjs().toObject()).toEqual(moment().toObject()) +}) From 2cd998fb91daec11482435a14d45a005c261424d Mon Sep 17 00:00:00 2001 From: iamkun Date: Thu, 7 Mar 2019 13:32:09 +0800 Subject: [PATCH 04/22] docs: update en doc --- docs/en/API-reference.md | 39 ++++++++++++++------------------------- docs/en/Plugin.md | 31 +++++++++++++++++++++++++++++++ 2 files changed, 45 insertions(+), 25 deletions(-) diff --git a/docs/en/API-reference.md b/docs/en/API-reference.md index 54ee2a3b6..f9d3cca67 100644 --- a/docs/en/API-reference.md +++ b/docs/en/API-reference.md @@ -39,10 +39,8 @@ The `Dayjs` object is immutable, that is, all API operations that change the `Da - [UTC offset (minutes) `.utcOffset()`](#utc-offset-minutes-utcoffset) - [Days in the Month `.daysInMonth()`](#days-in-the-month-daysinmonth) - [As Javascript Date `.toDate()`](#as-javascript-date-todate) - - [As Array `.toArray()`](#as-array-toarray) - [As JSON `.toJSON()`](#as-json-tojson) - [As ISO 8601 String `.toISOString()`](#as-iso-8601-string-toisostring) - - [As Object `.toObject()`](#as-object-toobject) - [As String `.toString()`](#as-string-tostring) - [Query](#query) - [Is Before `.isBefore(compared: Dayjs, unit?: string)`](#is-before-isbeforecompared-dayjs-unit-string) @@ -58,6 +56,8 @@ The `Dayjs` object is immutable, that is, all API operations that change the `Da - [IsSameOrBefore](#issameorbefore) - [IsBetween](#isbetween) - [QuarterOfYear](#quarterofyear) + - [ToArray](#toarray) + - [ToObject](#toobject) ## Parsing @@ -354,14 +354,6 @@ Returns a copy of the native `Date` object parsed from the `Dayjs` object. dayjs('2019-01-25').toDate() ``` -### As Array `.toArray()` - -Returns an `array` that mirrors the parameters from new Date(). - -```js -dayjs('2019-01-25').toArray() // [ 2019, 0, 25, 0, 0, 0, 0 ] -``` - ### As JSON `.toJSON()` Returns the `Dayjs` formatted in an ISO8601 `string`. @@ -378,21 +370,6 @@ Returns the `Dayjs` formatted in an ISO8601 `string`. dayjs('2019-01-25').toISOString() // '2019-01-25T02:00:00.000Z' ``` -### As Object `.toObject()` - -Returns an `object` with the date's properties. - -```js -dayjs('2019-01-25').toObject() -/* { years: 2019, - months: 0, - date: 25, - hours: 0, - minutes: 0, - seconds: 0, - milliseconds: 0 } */ -``` - ### As String `.toString()` Returns a `string` representation of the date. @@ -492,3 +469,15 @@ plugin [`IsBetween`](./Plugin.md#isbetween) `.quarter` to get quarter of the year plugin [`QuarterOfYear`](./Plugin.md#quarterofyear) + +### ToArray + +`.toArray` to return an `array` that mirrors the parameters + +plugin [`ToArray`](./Plugin.md#toarray) + +### ToObject + +`.toObject` to return an `object` with the date's properties. + +plugin [`ToObject`](./Plugin.md#toobject) diff --git a/docs/en/Plugin.md b/docs/en/Plugin.md index 56823fb09..87b1cb9db 100644 --- a/docs/en/Plugin.md +++ b/docs/en/Plugin.md @@ -340,6 +340,37 @@ dayjs('2018 Enero 15', 'YYYY MMMM DD', 'es') | `A` | AM PM | Post or ante meridiem, upper-case | | `a` | am pm | Post or ante meridiem, lower-case | +### ToArray + +- ToArray add `.toArray()` API to return an `array` that mirrors the parameters + +```javascript +import toArray from 'dayjs/plugin/toArray' + +dayjs.extend(toArray) + +dayjs('2019-01-25').toArray() // [ 2019, 0, 25, 0, 0, 0, 0 ] +``` + +### ToObject + +- ToObject add `.toObject()` API to return an `object` with the date's properties. + +```javascript +import toObject from 'dayjs/plugin/toObject' + +dayjs.extend(toObject) + +dayjs('2019-01-25').toObject() +/* { years: 2019, + months: 0, + date: 25, + hours: 0, + minutes: 0, + seconds: 0, + milliseconds: 0 } */ +``` + ## Customize You could build your own Day.js plugin to meet different needs. From 785405fb52a3aec0c6cc0bf9953502b548967691 Mon Sep 17 00:00:00 2001 From: iamkun Date: Thu, 7 Mar 2019 13:42:25 +0800 Subject: [PATCH 05/22] docs: update other docs --- docs/es-es/API-reference.md | 39 ++++++++++++-------------------- docs/es-es/Plugin.md | 31 ++++++++++++++++++++++++++ docs/ja/API-reference.md | 36 ++++++++++++------------------ docs/ja/Plugin.md | 31 ++++++++++++++++++++++++++ docs/ko/API-reference.md | 39 ++++++++++++-------------------- docs/ko/Plugin.md | 31 ++++++++++++++++++++++++++ docs/pt-br/API-reference.md | 39 ++++++++++++-------------------- docs/pt-br/Plugin.md | 31 ++++++++++++++++++++++++++ docs/zh-cn/API-reference.md | 44 +++++++++++++++---------------------- docs/zh-cn/Plugin.md | 31 ++++++++++++++++++++++++++ 10 files changed, 229 insertions(+), 123 deletions(-) diff --git a/docs/es-es/API-reference.md b/docs/es-es/API-reference.md index b165afcc3..bcb0dce43 100644 --- a/docs/es-es/API-reference.md +++ b/docs/es-es/API-reference.md @@ -39,10 +39,8 @@ El objeto `Dayjs` es inmutable, por lo que toda operación de la API que altere - [UTC offset (minutos) `.utcOffset()`](#utc-offset-minutos-utcoffset) - [Días en el mes `.daysInMonth()`](#días-en-el-mes-daysinmonth) - [Como objeto `Date` `.toDate()`](#como-objeto-date-todate) - - [Como array `.toArray()`](#como-array-toarray) - [Como JSON `.toJSON()`](#como-json-tojson) - [Como cadena ISO 8601 `.toISOString()`](#como-cadena-iso-8601-toisostring) - - [Como objeto `.toObject()`](#como-objecto-toobject) - [Como cadena `.toString()`](#como-cadena-tostring) - [Consulta](#consulta) - [Anterior a `.isBefore(compared: Dayjs, unit?: string)`](#anterior-a-isbeforecompared-dayjs-unit-string) @@ -58,6 +56,8 @@ El objeto `Dayjs` es inmutable, por lo que toda operación de la API que altere - [IsSameOrBefore](#issameorbefore) - [IsBetween](#isbetween) - [QuarterOfYear](#quarterofyear) + - [ToArray](#toarray) + - [ToObject](#toobject) ## Análisis @@ -354,14 +354,6 @@ Devuelve un objeto `Date` nativo, obtenido a partir del objeto `Dayjs`. dayjs('2019-01-25').toDate() ``` -### Como array `.toArray()` - -Devuelve un array que reproduce los parámetros de `new Date()`. - -```js -dayjs('2019-01-25').toArray() // [ 2019, 0, 25, 0, 0, 0, 0 ] -``` - ### Como JSON `.toJSON()` Devuelve un objeto `Dayjs` formateado como una cadena ISO8601. @@ -378,21 +370,6 @@ Devuelve un objeto `Dayjs` formateado como una cadena ISO8601. dayjs('2019-01-25').toISOString() // '2019-01-25T02:00:00.000Z' ``` -### Como objecto `.toObject()` - -Devuelve un dato de tipo `object`, con las propiedades de la fecha. - -```js -dayjs('2019-01-25').toObject() -/* { years: 2019, - months: 0, - date: 25, - hours: 0, - minutes: 0, - seconds: 0, - milliseconds: 0 } */ -``` - ### Como cadena `.toString()` Devuelve un dato de tipo `string`, que representa la fecha. @@ -492,3 +469,15 @@ complemento [`IsBetween`](./Plugin.md#isbetween) `.quarter` to get quarter of the year plugin [`QuarterOfYear`](./Plugin.md#quarterofyear) + +### ToArray + +`.toArray` to return an `array` that mirrors the parameters + +plugin [`ToArray`](./Plugin.md#toarray) + +### ToObject + +`.toObject` to return an `object` with the date's properties. + +plugin [`ToObject`](./Plugin.md#toobject) diff --git a/docs/es-es/Plugin.md b/docs/es-es/Plugin.md index 08256ab4a..4764cefb4 100644 --- a/docs/es-es/Plugin.md +++ b/docs/es-es/Plugin.md @@ -340,6 +340,37 @@ dayjs('2018 Enero 15', 'YYYY MMMM DD', 'es') | `A` | AM PM | Post or ante meridiem, upper-case | | `a` | am pm | Post or ante meridiem, lower-case | +### ToArray + +- ToArray add `.toArray()` API to return an `array` that mirrors the parameters + +```javascript +import toArray from 'dayjs/plugin/toArray' + +dayjs.extend(toArray) + +dayjs('2019-01-25').toArray() // [ 2019, 0, 25, 0, 0, 0, 0 ] +``` + +### ToObject + +- ToObject add `.toObject()` API to return an `object` with the date's properties. + +```javascript +import toObject from 'dayjs/plugin/toObject' + +dayjs.extend(toObject) + +dayjs('2019-01-25').toObject() +/* { years: 2019, + months: 0, + date: 25, + hours: 0, + minutes: 0, + seconds: 0, + milliseconds: 0 } */ +``` + ## Personalización Puedes construir tu propio complemento de Day.js para cubrir tus necesidades. diff --git a/docs/ja/API-reference.md b/docs/ja/API-reference.md index 57357a0da..53f2853a4 100644 --- a/docs/ja/API-reference.md +++ b/docs/ja/API-reference.md @@ -36,10 +36,8 @@ Day.js は組み込みの `Date.prototype` を変更する代わりに `Dayjs` - [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) @@ -55,6 +53,8 @@ Day.js は組み込みの `Date.prototype` を変更する代わりに `Dayjs` - [IsSameOrBefore](#issameorbefore) - [IsBetween](#isbetween) - [QuarterOfYear](#quarterofyear) + - [ToArray](#toarray) + - [ToObject](#toobject) --- @@ -408,16 +408,6 @@ dayjs().daysInMonth() dayjs().toDate() ``` -#### As Array - -- Array を返します - -Date コンストラクタパラメータに対応する値の配列を返します。 - -```js -dayjs().toArray() //[2018, 8, 18, 00, 00, 00, 000]; -``` - #### As JSON - JSON String を返します @@ -438,16 +428,6 @@ ISO8601 形式の文字列にフォーマットします。 dayjs().toISOString() ``` -#### As Object - -- Object を返します - -年、月、...(中略)...、ミリ秒のオブジェクトを返します。 - -```js -dayjs().toObject() // { years:2018, months:8, date:18, hours:0, minutes:0, seconds:0, milliseconds:0} -``` - #### As String - String を返します @@ -561,3 +541,15 @@ plugin [`IsBetween`](./Plugin.md#isbetween) `.quarter` to get quarter of the year plugin [`QuarterOfYear`](./Plugin.md#quarterofyear) + +### ToArray + +`.toArray` to return an `array` that mirrors the parameters + +plugin [`ToArray`](./Plugin.md#toarray) + +### ToObject + +`.toObject` to return an `object` with the date's properties. + +plugin [`ToObject`](./Plugin.md#toobject) diff --git a/docs/ja/Plugin.md b/docs/ja/Plugin.md index 22a3da15e..83cfaaf7d 100644 --- a/docs/ja/Plugin.md +++ b/docs/ja/Plugin.md @@ -349,6 +349,37 @@ dayjs('2018 5月 15', 'YYYY MMMM DD', 'ja') | `A` | AM PM | Post or ante meridiem, upper-case | | `a` | am pm | Post or ante meridiem, lower-case | +### ToArray + +- ToArray add `.toArray()` API to return an `array` that mirrors the parameters + +```javascript +import toArray from 'dayjs/plugin/toArray' + +dayjs.extend(toArray) + +dayjs('2019-01-25').toArray() // [ 2019, 0, 25, 0, 0, 0, 0 ] +``` + +### ToObject + +- ToObject add `.toObject()` API to return an `object` with the date's properties. + +```javascript +import toObject from 'dayjs/plugin/toObject' + +dayjs.extend(toObject) + +dayjs('2019-01-25').toObject() +/* { years: 2019, + months: 0, + date: 25, + hours: 0, + minutes: 0, + seconds: 0, + milliseconds: 0 } */ +``` + ## カスタマイズ さまざまなニーズに合わせて独自の Day.js プラグインを構築することができます。 diff --git a/docs/ko/API-reference.md b/docs/ko/API-reference.md index 62bcf83d0..f80d4c4e1 100644 --- a/docs/ko/API-reference.md +++ b/docs/ko/API-reference.md @@ -38,10 +38,8 @@ Day.js는 네이티브 `Date.prototype`을 수정하는 대신 `Dayjs` 오브젝 - [UTC offset (minutes) `.utcOffset()`](#utc-offset-minutes-utcoffset) - [Days in the Month `.daysInMonth()`](#days-in-the-month-daysinmonth) - [As Javascript Date `.toDate()`](#as-javascript-date-todate) - - [As Array `.toArray()`](#as-array-toarray) - [As JSON `.toJSON()`](#as-json-tojson) - [As ISO 8601 String `.toISOString()`](#as-iso-8601-string-toisostring) - - [As Object `.toObject()`](#as-object-toobject) - [As String `.toString()`](#as-string-tostring) - [Query](#query) - [Is Before `.isBefore(compared: Dayjs, unit?: string)`](#is-before-isbeforecompared--dayjs-unit-string) @@ -57,6 +55,8 @@ Day.js는 네이티브 `Date.prototype`을 수정하는 대신 `Dayjs` 오브젝 - [IsSameOrBefore](#issameorbefore) - [IsBetween](#isbetween) - [QuarterOfYear](#quarterofyear) + - [ToArray](#toarray) + - [ToObject](#toobject) ## Parsing @@ -353,14 +353,6 @@ dayjs('2019-01-25').daysInMonth() // 31 dayjs('2019-01-25').toDate() ``` -### As Array `.toArray()` - -새로운 `Date()`로부터 매개변수로 입력한 날짜를 가져옵니다. 반환 타입은 `array` 입니다. - -```js -dayjs('2019-01-25').toArray() // [ 2019, 01, 25, 0, 0, 0, 0 ] -``` - ### As JSON `.toJSON()` ISO8601에 대한 형식으로 `Dayjs`를 출력합니다. 반환 타입은 `string` 입니다. @@ -377,21 +369,6 @@ ISO8601에 대한 형식으로 `Dayjs`를 출력합니다. 반환 타입은 `str dayjs('2019-01-25').toISOString() // '2019-01-25T02:00:00.000Z' ``` -### As Object `.toObject()` - -날짜 속성을 가진 `object` 타입 값으로 반환합니다. - -```js -dayjs('2019-01-25').toObject() -/* { years: 2019, - months: 0, - date: 25, - hours: 0, - minutes: 0, - seconds: 0, - milliseconds: 0 } */ -``` - ### As String `.toString()` 날짜를 `string` 타입 값으로 반환합니다. @@ -491,3 +468,15 @@ plugin [`IsBetween`](./Plugin.md#isbetween) `.quarter` to get quarter of the year plugin [`QuarterOfYear`](./Plugin.md#quarterofyear) + +### ToArray + +`.toArray` to return an `array` that mirrors the parameters + +plugin [`ToArray`](./Plugin.md#toarray) + +### ToObject + +`.toObject` to return an `object` with the date's properties. + +plugin [`ToObject`](./Plugin.md#toobject) diff --git a/docs/ko/Plugin.md b/docs/ko/Plugin.md index 8463ae241..267be0ce1 100644 --- a/docs/ko/Plugin.md +++ b/docs/ko/Plugin.md @@ -341,6 +341,37 @@ dayjs('2018 5월 15', 'YYYY MMMM DD', 'ko') | `A` | AM PM | Post or ante meridiem, upper-case | | `a` | am pm | Post or ante meridiem, lower-case | +### ToArray + +- ToArray add `.toArray()` API to return an `array` that mirrors the parameters + +```javascript +import toArray from 'dayjs/plugin/toArray' + +dayjs.extend(toArray) + +dayjs('2019-01-25').toArray() // [ 2019, 0, 25, 0, 0, 0, 0 ] +``` + +### ToObject + +- ToObject add `.toObject()` API to return an `object` with the date's properties. + +```javascript +import toObject from 'dayjs/plugin/toObject' + +dayjs.extend(toObject) + +dayjs('2019-01-25').toObject() +/* { years: 2019, + months: 0, + date: 25, + hours: 0, + minutes: 0, + seconds: 0, + milliseconds: 0 } */ +``` + ## Customize 다양한 요구를 충족하기위해 자신만의 Day.js 플러그인을 만들 수 있습니다. diff --git a/docs/pt-br/API-reference.md b/docs/pt-br/API-reference.md index baa9857d7..2a546378a 100644 --- a/docs/pt-br/API-reference.md +++ b/docs/pt-br/API-reference.md @@ -39,10 +39,8 @@ O objeto `Dayjs` é imutável, ou seja, todas as operações da API que alteram - [UTC offset (minutes) `.utcOffset()`](#utc-offset-minutes-utcoffset) - [Dias no Mês `.daysInMonth()`](#dias-no-mês-daysinmonth) - [Como objeto `Date` do Javascript `.toDate()`](#como-objeto-date-do-javascript-todate) - - [Como Array `.toArray()`](#como-array-toarray) - [Como JSON `.toJSON()`](#como-json-tojson) - [Como uma string ISO 8601 `.toISOString()`](#como-uma-string-iso-8601-toisostring) - - [Como Objeto `.toObject()`](#como-objeto-toobject) - [Como String `.toString()`](#como-string-tostring) - [Consulta](#consulta) - [Antes `.isBefore(compared: Dayjs, unit?: string)`](#antes-isbeforecompared-dayjs-unit-string) @@ -58,6 +56,8 @@ O objeto `Dayjs` é imutável, ou seja, todas as operações da API que alteram - [IsSameOrBefore](#issameorbefore) - [IsBetween](#isbetween) - [QuarterOfYear](#quarterofyear) + - [ToArray](#toarray) + - [ToObject](#toobject) ## Conversões @@ -352,14 +352,6 @@ Retorna uma cópia do objeto nativo `Date` convertido de um objeto `Dayjs`. dayjs('2019-01-25').toDate() ``` -### Como Array `.toArray()` - -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 ] -``` - ### Como JSON `.toJSON()` Retorna o objeto `Dayjs` formatado em uma `string` ISO8601. @@ -376,21 +368,6 @@ Retorna o objeto `Dayjs` formatado em uma `string` ISO8601. dayjs('2019-01-25').toISOString() // '2019-01-25T02:00:00.000Z' ``` -### Como Objeto `.toObject()` - -Retorna um `object` com as propriedades da data. - -```js -dayjs('2019-01-25').toObject() -/* { years: 2019, - months: 0, - date: 25, - hours: 0, - minutes: 0, - seconds: 0, - milliseconds: 0 } */ -``` - ### Como String `.toString()` Retorna uma representação em `string` da data. @@ -490,3 +467,15 @@ plugin [`IsBetween`](./Plugin.md#isbetween) `.quarter` to get quarter of the year plugin [`QuarterOfYear`](./Plugin.md#quarterofyear) + +### ToArray + +`.toArray` to return an `array` that mirrors the parameters + +plugin [`ToArray`](./Plugin.md#toarray) + +### ToObject + +`.toObject` to return an `object` with the date's properties. + +plugin [`ToObject`](./Plugin.md#toobject) diff --git a/docs/pt-br/Plugin.md b/docs/pt-br/Plugin.md index 687cea35f..ae5f29d99 100644 --- a/docs/pt-br/Plugin.md +++ b/docs/pt-br/Plugin.md @@ -340,6 +340,37 @@ dayjs('2018 Fevereiro 15', 'YYYY MMMM DD', 'pt_br') | `A` | AM PM | Post or ante meridiem, upper-case | | `a` | am pm | Post or ante meridiem, lower-case | +### ToArray + +- ToArray add `.toArray()` API to return an `array` that mirrors the parameters + +```javascript +import toArray from 'dayjs/plugin/toArray' + +dayjs.extend(toArray) + +dayjs('2019-01-25').toArray() // [ 2019, 0, 25, 0, 0, 0, 0 ] +``` + +### ToObject + +- ToObject add `.toObject()` API to return an `object` with the date's properties. + +```javascript +import toObject from 'dayjs/plugin/toObject' + +dayjs.extend(toObject) + +dayjs('2019-01-25').toObject() +/* { years: 2019, + months: 0, + date: 25, + hours: 0, + minutes: 0, + seconds: 0, + milliseconds: 0 } */ +``` + ## Customizar Você também pode construir seu próprio plugin Day.js para diferentes necessidades. diff --git a/docs/zh-cn/API-reference.md b/docs/zh-cn/API-reference.md index 468fa65ee..32bc56b02 100644 --- a/docs/zh-cn/API-reference.md +++ b/docs/zh-cn/API-reference.md @@ -36,10 +36,8 @@ - [UTC 偏移量 (分)](#utc-偏移量-分) - [天数 (月)](#天数-月) - [Date 对象](#date-对象-1) - - [数组](#数组) - [JSON](#as-json) - [ISO 8601 字符串](#iso-8601-字符串) - - [对象](#对象) - [字符串](#字符串) - [查询](#查询) - [是否之前](#是否之前) @@ -55,6 +53,8 @@ - [是否相同或之前](#是否相同或之前) - [是否之间](#是否之间) - [年中第几季度](#年中第几季度) + - [转成数组](#转成数组) + - [转成对象](#转成对象) --- @@ -406,16 +406,6 @@ dayjs().daysInMonth() dayjs().toDate() ``` -#### 数组 - -- return Array - -返回包含时间数值的数组。 - -```js -dayjs().toArray() //[2018, 8, 18, 00, 00, 00, 000]; -``` - #### As JSON - return JSON String @@ -436,16 +426,6 @@ dayjs().toJSON() //"2018-08-08T00:00:00.000Z" dayjs().toISOString() ``` -#### 对象 - -- return Object - -返回包含时间数值的对象。 - -```js -dayjs().toObject() // { years:2018, months:8, date:18, hours:0, minutes:0, seconds:0, milliseconds:0} -``` - #### 字符串 - return String @@ -537,22 +517,34 @@ dayjs() instanceof dayjs // true `.isSameOrAfter` 返回一个时间和一个时间相同或在一个时间之后 -plugin [`IsSameOrAfter`](./Plugin.md#issameorafter) +插件 [`IsSameOrAfter`](./Plugin.md#issameorafter) ### 是否相同或之前 `.isSameOrBefore` 返回一个时间是否和一个时间相同或在一个时间之前 -plugin [`IsSameOrBefore`](./Plugin.md#issameorbefore) +插件 [`IsSameOrBefore`](./Plugin.md#issameorbefore) ### 是否之间 `.isBetween` 返回一个时间是否介于两个时间之间 -plugin [`IsBetween`](./Plugin.md#isbetween) +插件 [`IsBetween`](./Plugin.md#isbetween) ### 年中第几季度 `.quarter` 返回年中第几季度 -plugin [`QuarterOfYear`](./Plugin.md#quarterofyear) +插件 [`QuarterOfYear`](./Plugin.md#quarterofyear) + +### 转成数组 + +`.toArray` 返回包含时间数值的数组。 + +插件 [`ToArray`](./Plugin.md#toarray) + +### 转成对象 + +`.toObject` 返回包含时间数值的对象 + +插件 [`ToObject`](./Plugin.md#toobject) diff --git a/docs/zh-cn/Plugin.md b/docs/zh-cn/Plugin.md index 6aa714614..909038ee6 100644 --- a/docs/zh-cn/Plugin.md +++ b/docs/zh-cn/Plugin.md @@ -339,6 +339,37 @@ dayjs('2018 五月 15', 'YYYY MMMM DD', 'zh_cn') | `A` | AM PM | | | `a` | am pm | | +### ToArray + +- ToArray 增加了 `.toArray()` API 来返回包含时间数值的数组。 + +```javascript +import toArray from 'dayjs/plugin/toArray' + +dayjs.extend(toArray) + +dayjs('2019-01-25').toArray() // [ 2019, 0, 25, 0, 0, 0, 0 ] +``` + +### ToObject + +- ToObject 增加了 `.toObject()` API 来返回包含时间数值的对象。 + +```javascript +import toObject from 'dayjs/plugin/toObject' + +dayjs.extend(toObject) + +dayjs('2019-01-25').toObject() +/* { years: 2019, + months: 0, + date: 25, + hours: 0, + minutes: 0, + seconds: 0, + milliseconds: 0 } */ +``` + ## 自定义 你可以根据需要自由的编写一个 Day.js 插件 From ac532a0f0a003911bb22c395245bfe6433fd1c7b Mon Sep 17 00:00:00 2001 From: iamkun Date: Thu, 7 Mar 2019 14:02:52 +0800 Subject: [PATCH 06/22] fix: Expand setters like .year(2000) .hour(12) --- src/index.js | 37 +++++++++++++++++++++---------------- test/get-set.test.js | 16 ++++++++++++++++ 2 files changed, 37 insertions(+), 16 deletions(-) diff --git a/src/index.js b/src/index.js index 55e5d647f..112ae33b0 100644 --- a/src/index.js +++ b/src/index.js @@ -109,36 +109,41 @@ class Dayjs { return this.endOf(units) < dayjs(that) } - year() { - return this.$y + $g(input, get, set) { + if (Utils.u(input)) return this[get] + return this.set(set, input) } - month() { - return this.$M + year(input) { + return this.$g(input, '$y', C.Y) } - day() { - return this.$W + month(input) { + return this.$g(input, '$M', C.M) } - date() { - return this.$D + day(input) { + return this.$g(input, '$W', C.D) } - hour() { - return this.$H + date(input) { + return this.$g(input, '$D', C.DATE) } - minute() { - return this.$m + hour(input) { + return this.$g(input, '$H', C.H) } - second() { - return this.$s + minute(input) { + return this.$g(input, '$m', C.MIN) } - millisecond() { - return this.$ms + second(input) { + return this.$g(input, '$s', C.S) + } + + millisecond(input) { + return this.$g(input, '$ms', C.MS) } unix() { diff --git a/test/get-set.test.js b/test/get-set.test.js index af5676a38..7587915cf 100644 --- a/test/get-set.test.js +++ b/test/get-set.test.js @@ -12,34 +12,50 @@ afterEach(() => { it('Year', () => { expect(dayjs().year()).toBe(moment().year()) + expect(dayjs().year(0).valueOf()).toBe(moment().year(0).valueOf()) + expect(dayjs().year(2000).valueOf()).toBe(moment().year(2000).valueOf()) }) it('Month', () => { expect(dayjs().month()).toBe(moment().month()) + expect(dayjs().month(0).valueOf()).toBe(moment().month(0).valueOf()) + expect(dayjs().month(1).valueOf()).toBe(moment().month(1).valueOf()) }) it('Day of Week', () => { expect(dayjs().day()).toBe(moment().day()) + expect(dayjs().day(0).format()).toBe(moment().day(0).format()) + expect(dayjs().day(1).format()).toBe(moment().day(1).format()) }) it('Date', () => { expect(dayjs().date()).toBe(moment().date()) + expect(dayjs().date(0).valueOf()).toBe(moment().date(0).valueOf()) + expect(dayjs().date(1).valueOf()).toBe(moment().date(1).valueOf()) }) it('Hour', () => { expect(dayjs().hour()).toBe(moment().hour()) + expect(dayjs().hour(0).valueOf()).toBe(moment().hour(0).valueOf()) + expect(dayjs().hour(1).valueOf()).toBe(moment().hour(1).valueOf()) }) it('Minute', () => { expect(dayjs().minute()).toBe(moment().minute()) + expect(dayjs().minute(0).valueOf()).toBe(moment().minute(0).valueOf()) + expect(dayjs().minute(1).valueOf()).toBe(moment().minute(1).valueOf()) }) it('Second', () => { expect(dayjs().second()).toBe(moment().second()) + expect(dayjs().second(0).valueOf()).toBe(moment().second(0).valueOf()) + expect(dayjs().second(1).valueOf()).toBe(moment().second(1).valueOf()) }) it('Millisecond', () => { expect(dayjs().millisecond()).toBe(moment().millisecond()) + expect(dayjs().millisecond(0).valueOf()).toBe(moment().millisecond(0).valueOf()) + expect(dayjs().millisecond(1).valueOf()).toBe(moment().millisecond(1).valueOf()) }) it('Set Day', () => { From a075cfa7649def835fcc88ef6bfb6b4d94234f4c Mon Sep 17 00:00:00 2001 From: iamkun Date: Thu, 7 Mar 2019 14:10:41 +0800 Subject: [PATCH 07/22] chore: update types --- types/index.d.ts | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/types/index.d.ts b/types/index.d.ts index abadb4692..eee848e61 100644 --- a/types/index.d.ts +++ b/types/index.d.ts @@ -21,20 +21,36 @@ declare namespace dayjs { year(): number + year(value: number): Dayjs + month(): number + month(value: number): Dayjs + date(): number + date(value: number): Dayjs + day(): number + day(value: number): Dayjs + hour(): number + hour(value: number): Dayjs + minute(): number + minute(value: number): Dayjs + second(): number + second(value: number): Dayjs + millisecond(): number + millisecond(value: number): Dayjs + set(unit: UnitType, value: number): Dayjs add(value: number, unit: OpUnitType): Dayjs From 92f4e72c1218f37dcd4d00b4c07b049fc2da9215 Mon Sep 17 00:00:00 2001 From: iamkun Date: Thu, 7 Mar 2019 14:33:06 +0800 Subject: [PATCH 08/22] docs: update get+set doc en --- docs/en/API-reference.md | 24 ++++++++++++++++-------- 1 file changed, 16 insertions(+), 8 deletions(-) diff --git a/docs/en/API-reference.md b/docs/en/API-reference.md index f9d3cca67..53102fec1 100644 --- a/docs/en/API-reference.md +++ b/docs/en/API-reference.md @@ -125,66 +125,74 @@ dayjs().isValid() ### Year `.year()` -Returns a `number` representing the `Dayjs`'s year. +Gets or sets the year. ```js dayjs().year() +dayjs().year(2000) ``` ### Month `.month()` -Returns a `number` representing the `Dayjs`'s month. Starts at 0 +Gets or sets the month. Starts at 0 ```js dayjs().month() +dayjs().month(0) ``` ### Day of the Month `.date()` -Returns a `number` representing the `Dayjs`'s day of the month. Starts at 1 +Gets or sets the day of the month. Starts at 1 ```js dayjs().date() +dayjs().date(1) ``` ### Day of the Week `.day()` -Returns a `number` representing the `Dayjs`'s day of the week. Starts on Sunday with 0 +Gets or sets the day of the week. Starts on Sunday with 0 ```js dayjs().day() +dayjs().day(0) ``` ### Hour `.hour()` -Returns a `number` representing the `Dayjs`'s hour. +Gets or sets the hour. ```js dayjs().hour() +dayjs().hour(12) ``` ### Minute `.minute()` -Returns a `number` representing the `Dayjs`'s minute. +Gets or sets the minute. ```js dayjs().minute() +dayjs().minute(59) ``` ### Second `.second()` -Returns a `number` representing the `Dayjs`'s second. +Gets or sets the second. ```js dayjs().second() +dayjs().second(1) ``` ### Millisecond `.millisecond()` -Returns a `number` representing the `Dayjs`'s millisecond. +Gets or sets the millisecond. ```js dayjs().millisecond() +dayjs().millisecond(1) ``` ### Set `.set(unit: string, value: number)` From fbb88995f1b45d18820d6fe0ada6cef89204fdac Mon Sep 17 00:00:00 2001 From: iamkun Date: Thu, 7 Mar 2019 14:54:10 +0800 Subject: [PATCH 09/22] docs: update set+get docs --- docs/es-es/API-reference.md | 24 ++++++++++++++-------- docs/ja/API-reference.md | 40 +++++++++++++++---------------------- docs/ko/API-reference.md | 24 ++++++++++++++-------- docs/pt-br/API-reference.md | 24 ++++++++++++++-------- docs/zh-cn/API-reference.md | 40 +++++++++++++++---------------------- 5 files changed, 80 insertions(+), 72 deletions(-) diff --git a/docs/es-es/API-reference.md b/docs/es-es/API-reference.md index bcb0dce43..d26c925a4 100644 --- a/docs/es-es/API-reference.md +++ b/docs/es-es/API-reference.md @@ -125,66 +125,74 @@ dayjs().isValid() ### Año `.year()` -Devuelve un dato de tipo `number`, que representa el año del objeto `Dayjs`. +Gets or sets the year. ```js dayjs().year() +dayjs().year(2000) ``` ### Mes `.month()` -Devuelve un dato de tipo `number`, que representa el mes del objeto `Dayjs`. Se cuenta desde 0, que se corresponde con enero. +Gets or sets the month. Starts at 0 ```js dayjs().month() +dayjs().month(0) ``` ### Día del mes `.date()` -Devuelve un dato de tipo `number`, que indica el día del mes del objeto `Dayjs`. Empieza por el día 1. +Gets or sets the day of the month. Starts at 1 ```js dayjs().date() +dayjs().date(1) ``` ### Día de la semana `.day()` -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. +Gets or sets the day of the week. Starts on Sunday with 0 ```js dayjs().day() +dayjs().day(0) ``` ### Hora `.hour()` -Devuelve un dato de tipo `number`, que indica la hora del objeto `Dayjs`. +Gets or sets the hour. ```js dayjs().hour() +dayjs().hour(12) ``` ### Minuto `.minute()` -Devuelve un dato de tipo `number`, que indica los minutos del objeto `Dayjs`. +Gets or sets the minute. ```js dayjs().minute() +dayjs().minute(59) ``` ### Segundo `.second()` -Devuelve un dato de tipo `number`, que indica los segundos del objeto `Dayjs`. +Gets or sets the second. ```js dayjs().second() +dayjs().second(1) ``` ### Milisegundo `.millisecond()` -Devuelve un dato de tipo `number`, que indica los milisegundos del objeto `Dayjs`. +Gets or sets the millisecond. ```js dayjs().millisecond() +dayjs().millisecond(1) ``` ### Set `.set(unit: string, value: number)` diff --git a/docs/ja/API-reference.md b/docs/ja/API-reference.md index 53f2853a4..57daefcbe 100644 --- a/docs/ja/API-reference.md +++ b/docs/ja/API-reference.md @@ -138,82 +138,74 @@ dayjs().isValid() #### Year -- Number を返します - -年を取得します。 +Gets or sets the year. ```js dayjs().year() +dayjs().year(2000) ``` #### Month -- Number を返します - -月を取得します。 +Gets or sets the month. Starts at 0 ```js dayjs().month() +dayjs().month(0) ``` #### Date of Month -- Number を返します - -日を取得します。 +Gets or sets the day of the month. Starts at 1 ```js dayjs().date() +dayjs().date(1) ``` #### Day of Week -- Number を返します - -曜日を取得します。 +Gets or sets the day of the week. Starts on Sunday with 0 ```js dayjs().day() +dayjs().day(0) ``` #### Hour -- Number を返します - -時間を取得します。 +Gets or sets the hour. ```js dayjs().hour() +dayjs().hour(12) ``` #### Minute -- Number を返します - -分を取得します。 +Gets or sets the minute. ```js dayjs().minute() +dayjs().minute(59) ``` #### Second -- Number を返します - -秒を取得します。 +Gets or sets the second. ```js dayjs().second() +dayjs().second(1) ``` #### Millisecond -- Number を返します - -ミリ秒を取得します。 +Gets or sets the millisecond. ```js dayjs().millisecond() +dayjs().millisecond(1) ``` #### Set diff --git a/docs/ko/API-reference.md b/docs/ko/API-reference.md index f80d4c4e1..01fa80488 100644 --- a/docs/ko/API-reference.md +++ b/docs/ko/API-reference.md @@ -124,66 +124,74 @@ dayjs().isValid() ### Year `.year()` -`Dayjs`에서 연도 가져옵니다. 반환 타입은 `number` 입니다. +Gets or sets the year. ```js dayjs().year() +dayjs().year(2000) ``` ### Month `.month()` -`Dayjs`에서 달을 가져옵니다. 반환 타입은 `number` 입니다. +Gets or sets the month. Starts at 0 ```js dayjs().month() +dayjs().month(0) ``` ### Day of the Month `.date()` -`Dayjs`에서 날짜를 가져옵니다. 반환 타입은 `number` 입니다. +Gets or sets the day of the month. Starts at 1 ```js dayjs().date() +dayjs().date(1) ``` ### Day of the Week `.day()` -`Dayjs`에서 요일을 가져옵니다. 반환 타입은 `number` 입니다. +Gets or sets the day of the week. Starts on Sunday with 0 ```js dayjs().day() +dayjs().day(0) ``` ### Hour `.hour()` -`Dayjs`에서 시를 가져옵니다. 반환 타입은 `number` 입니다. +Gets or sets the hour. ```js dayjs().hour() +dayjs().hour(12) ``` ### Minute `.minute()` -`Dayjs`에서 분을 가져옵니다. 반환 타입은 `number` 입니다. +Gets or sets the minute. ```js dayjs().minute() +dayjs().minute(59) ``` ### Second `.second()` -`Dayjs`에서 초를 가져옵니다. 반환 타입은 `number` 입니다. +Gets or sets the second. ```js dayjs().second() +dayjs().second(1) ``` ### Millisecond `.millisecond()` -`Dayjs`에서 밀리 초를 가져옵니다. 반환 타입은 `number` 입니다. +Gets or sets the millisecond. ```js dayjs().millisecond() +dayjs().millisecond(1) ``` ### Set `.set(unit: string, value: number)` diff --git a/docs/pt-br/API-reference.md b/docs/pt-br/API-reference.md index 2a546378a..2213127c4 100644 --- a/docs/pt-br/API-reference.md +++ b/docs/pt-br/API-reference.md @@ -123,66 +123,74 @@ dayjs().isValid() ### Ano `.year()` -Retorna um `number` representando o ano do objeto `Dayjs`. +Gets or sets the year. ```js dayjs().year() +dayjs().year(2000) ``` ### Mês `.month()` -Retorna um `number` representando o mês do objeto `Dayjs`. +Gets or sets the month. Starts at 0 ```js dayjs().month() +dayjs().month(0) ``` ### Dia do Mês `.date()` -Retorna um `number` representando o dia do mês do objeto `Dayjs`. +Gets or sets the day of the month. Starts at 1 ```js dayjs().date() +dayjs().date(1) ``` ### Dia da Semana `.day()` -Retorna um `number` representando o dia da semana do objeto `Dayjs`. +Gets or sets the day of the week. Starts on Sunday with 0 ```js dayjs().day() +dayjs().day(0) ``` ### Hora `.hour()` -Retorna um `number` representando a hora do objeto `Dayjs`. +Gets or sets the hour. ```js dayjs().hour() +dayjs().hour(12) ``` ### Minuto `.minute()` -Retorna um `number` representando os minutos do objeto `Dayjs`. +Gets or sets the minute. ```js dayjs().minute() +dayjs().minute(59) ``` ### Segundo `.second()` -Retorna um `number` representando os segundos do objeto `Dayjs`. +Gets or sets the second. ```js dayjs().second() +dayjs().second(1) ``` ### Milissegundo `.millisecond()` -Retorna um `number` representando os milissegundos do objeto `Dayjs`. +Gets or sets the millisecond. ```js dayjs().millisecond() +dayjs().millisecond(1) ``` ### Set `.set(unit: string, value: number)` diff --git a/docs/zh-cn/API-reference.md b/docs/zh-cn/API-reference.md index 32bc56b02..aa96f2891 100644 --- a/docs/zh-cn/API-reference.md +++ b/docs/zh-cn/API-reference.md @@ -140,82 +140,74 @@ dayjs().isValid() #### 年 -- return Number - -获取年份。 +获取或设置年份。 ```js dayjs().year() +dayjs().year(2000) ``` #### 月 -- return Number - -获取月份。 +获取或设置月份。从 0 开始 ```js dayjs().month() +dayjs().month(0) ``` #### 日 -- return Number - -获取日期。 +获取或设置日期。从 1 开始 ```js dayjs().date() +dayjs().date(1) ``` #### 星期 -- return Number - -获取星期。 +获取或设置星期。从星期天 0 开始 ```js dayjs().day() +dayjs().day(0) ``` #### 时 -- return Number - -获取小时。 +获取或设置小时。 ```js dayjs().hour() +dayjs().hour(12) ``` #### 分 -- return Number - -获取分钟。 +获取或设置分钟。 ```js dayjs().minute() +dayjs().minute(59) ``` #### 秒 -- return Number - -获取秒。 +获取或设置秒。 ```js dayjs().second() +dayjs().second(1) ``` #### 毫秒 -- return Number - -获取毫秒。 +获取或设置毫秒。 ```js dayjs().millisecond() +dayjs().millisecond(1) ``` #### 设置 From 5f7e7c4e4489f254c78ca13468e5d50d9aab955f Mon Sep 17 00:00:00 2001 From: iamkun Date: Thu, 7 Mar 2019 17:50:23 +0800 Subject: [PATCH 10/22] chore: Add isMoment plugin --- src/plugin/isMoment/index.js | 6 ++++++ test/plugin/isMoment.test.js | 18 ++++++++++++++++++ types/plugin/isMoment.d.ts | 10 ++++++++++ 3 files changed, 34 insertions(+) create mode 100644 src/plugin/isMoment/index.js create mode 100644 test/plugin/isMoment.test.js create mode 100644 types/plugin/isMoment.d.ts diff --git a/src/plugin/isMoment/index.js b/src/plugin/isMoment/index.js new file mode 100644 index 000000000..05c58f9ea --- /dev/null +++ b/src/plugin/isMoment/index.js @@ -0,0 +1,6 @@ +export default (o, c, f) => { + f.isMoment = function (input) { + return f.isDayjs(input) + } +} + diff --git a/test/plugin/isMoment.test.js b/test/plugin/isMoment.test.js new file mode 100644 index 000000000..0c83e52ce --- /dev/null +++ b/test/plugin/isMoment.test.js @@ -0,0 +1,18 @@ +import MockDate from 'mockdate' +import dayjs from '../../src' +import isMoment from '../../src/plugin/isMoment' + +dayjs.extend(isMoment) + +beforeEach(() => { + MockDate.set(new Date()) +}) + +afterEach(() => { + MockDate.reset() +}) + +it('IsLeapYear', () => { + expect(dayjs.isMoment(dayjs())).toBe(true) + expect(dayjs.isMoment(new Date())).toBe(false) +}) diff --git a/types/plugin/isMoment.d.ts b/types/plugin/isMoment.d.ts new file mode 100644 index 000000000..d7ee3cff3 --- /dev/null +++ b/types/plugin/isMoment.d.ts @@ -0,0 +1,10 @@ +import { PluginFunc } from 'dayjs' + +declare const plugin: PluginFunc +export = plugin + +declare module 'dayjs' { + + export function utc(input: any): boolean + +} From f18a6e57c8f46db92dc1365f5537ad4e530bf952 Mon Sep 17 00:00:00 2001 From: iamkun Date: Thu, 7 Mar 2019 17:51:41 +0800 Subject: [PATCH 11/22] chore: fix typo --- types/plugin/isMoment.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/types/plugin/isMoment.d.ts b/types/plugin/isMoment.d.ts index d7ee3cff3..dac24f6f7 100644 --- a/types/plugin/isMoment.d.ts +++ b/types/plugin/isMoment.d.ts @@ -5,6 +5,6 @@ export = plugin declare module 'dayjs' { - export function utc(input: any): boolean - + export function isMoment(input: any): boolean + } From 08be44a9d9cc7137b732bc3d07edda3bec924a67 Mon Sep 17 00:00:00 2001 From: iamkun Date: Thu, 7 Mar 2019 18:34:04 +0800 Subject: [PATCH 12/22] chore: Add badMutable plugin --- src/index.js | 6 +- src/plugin/badMutable/index.js | 26 ++++++ test/plugin/badMutable.test.js | 150 +++++++++++++++++++++++++++++++++ types/plugin/badMutable.d.ts | 4 + 4 files changed, 184 insertions(+), 2 deletions(-) create mode 100644 src/plugin/badMutable/index.js create mode 100644 test/plugin/badMutable.test.js create mode 100644 types/plugin/badMutable.d.ts diff --git a/src/index.js b/src/index.js index 112ae33b0..a80fcd3ac 100644 --- a/src/index.js +++ b/src/index.js @@ -232,7 +232,8 @@ class Dayjs { number = Number(number) // eslint-disable-line no-param-reassign const unit = Utils.p(units) const instanceFactory = (u, n) => { - const date = this.set(C.DATE, 1).set(u, n + number) + // clone is for badMutable plugin + const date = this.clone().set(C.DATE, 1).set(u, n + number) return date.set(C.DATE, Math.min(this.$D, date.daysInMonth())) } const instanceFactorySet = (n) => { @@ -343,7 +344,8 @@ class Dayjs { } daysInMonth() { - return this.endOf(C.M).$D + // clone is for badMutable plugin + return this.clone().endOf(C.M).$D } $locale() { // get locale object diff --git a/src/plugin/badMutable/index.js b/src/plugin/badMutable/index.js new file mode 100644 index 000000000..d8c362400 --- /dev/null +++ b/src/plugin/badMutable/index.js @@ -0,0 +1,26 @@ +export default (o, c) => { // locale needed later + const proto = c.prototype + proto.$g = function (input, get, set) { + if (this.$utils().u(input)) return this[get] + return this.$set(set, input) + } + + proto.set = function (string, int) { + return this.$set(string, int) + } + + const oldStartOf = proto.startOf + proto.startOf = function (units, startOf) { + this.$d = oldStartOf.bind(this)(units, startOf).toDate() + this.init() + return this + } + + const oldAdd = proto.add + proto.add = function (number, units) { + this.$d = oldAdd.bind(this)(number, units).toDate() + this.init() + return this + } +} + diff --git a/test/plugin/badMutable.test.js b/test/plugin/badMutable.test.js new file mode 100644 index 000000000..e2413df84 --- /dev/null +++ b/test/plugin/badMutable.test.js @@ -0,0 +1,150 @@ +import MockDate from 'mockdate' +import moment from 'moment' +import dayjs from '../../src' +import badMutable from '../../src/plugin/badMutable' + +dayjs.extend(badMutable) + +beforeEach(() => { + MockDate.set(new Date()) +}) + +afterEach(() => { + MockDate.reset() +}) + +describe('Set', () => { + it('Setters', () => { + const d = dayjs() + const m = moment() + expect(d.year()).toBe(m.year()) + d.year(2000) + m.year(2000) + expect(d.format()).toBe(m.format()) + d.month(1) + m.month(1) + expect(d.format()).toBe(m.format()) + d.day(1) + m.day(1) + expect(d.format()).toBe(m.format()) + d.date(1) + m.date(1) + expect(d.format()).toBe(m.format()) + d.hour(1) + m.hour(1) + expect(d.format()).toBe(m.format()) + d.minute(1) + m.minute(1) + expect(d.format()).toBe(m.format()) + d.second(1) + m.second(1) + expect(d.format()).toBe(m.format()) + d.millisecond(1) + m.millisecond(1) + expect(d.format()).toBe(m.format()) + }) + + it('Set', () => { + const d = dayjs() + const m = moment() + d.set('year', 2000) + m.set('year', 2000) + expect(d.format()).toBe(m.format()) + d.set('month', 12) + m.set('month', 12) + expect(d.format()).toBe(m.format()) + d.set('day', 1) + m.set('day', 1) + expect(d.format()).toBe(m.format()) + d.set('date', 1) + m.set('date', 1) + expect(d.format()).toBe(m.format()) + d.set('hour', 1) + m.set('hour', 1) + expect(d.format()).toBe(m.format()) + d.set('minute', 1) + m.set('minute', 1) + expect(d.format()).toBe(m.format()) + d.set('second', 1) + m.set('second', 1) + expect(d.format()).toBe(m.format()) + d.set('millisecond', 1) + m.set('millisecond', 1) + expect(d.format()).toBe(m.format()) + }) +}) + +describe('StartOf', () => { + it('StartOf', () => { + const d = dayjs() + const m = moment() + d.startOf('year') + m.startOf('year') + expect(d.format()).toBe(m.format()) + d.startOf('month') + m.startOf('month') + expect(d.format()).toBe(m.format()) + d.startOf('day') + m.startOf('day') + expect(d.format()).toBe(m.format()) + d.startOf('date') + m.startOf('date') + expect(d.format()).toBe(m.format()) + d.startOf('hour') + m.startOf('hour') + expect(d.format()).toBe(m.format()) + d.startOf('minute') + m.startOf('minute') + expect(d.format()).toBe(m.format()) + d.startOf('second') + m.startOf('second') + expect(d.format()).toBe(m.format()) + d.startOf('millisecond') + m.startOf('millisecond') + expect(d.format()).toBe(m.format()) + d.startOf('week') + m.startOf('week') + expect(d.format()).toBe(m.format()) + }) +}) + +describe('Add', () => { + it('Add', () => { + const d = dayjs() + const m = moment() + d.add(1, 'year') + m.add(1, 'year') + expect(d.format()).toBe(m.format()) + d.add(12, 'month') + m.add(12, 'month') + expect(d.format()).toBe(m.format()) + d.add(1, 'day') + m.add(1, 'day') + expect(d.format()).toBe(m.format()) + d.add(1, 'date') + m.add(1, 'date') + expect(d.format()).toBe(m.format()) + d.add(1, 'hour') + m.add(1, 'hour') + expect(d.format()).toBe(m.format()) + d.add(1, 'minute') + m.add(1, 'minute') + expect(d.format()).toBe(m.format()) + d.add(1, 'second') + m.add(1, 'second') + expect(d.format()).toBe(m.format()) + d.add(1, 'millisecond') + m.add(1, 'millisecond') + expect(d.format()).toBe(m.format()) + d.add(1, 'week') + m.add(1, 'week') + expect(d.format()).toBe(m.format()) + }) +}) + +it('daysInMonth', () => { + const d = dayjs() + const m = moment() + expect(d.daysInMonth()).toBe(m.daysInMonth()) + expect(d.format()).toBe(m.format()) +}) diff --git a/types/plugin/badMutable.d.ts b/types/plugin/badMutable.d.ts new file mode 100644 index 000000000..30ec75e5d --- /dev/null +++ b/types/plugin/badMutable.d.ts @@ -0,0 +1,4 @@ +import { PluginFunc } from 'dayjs' + +declare const plugin: PluginFunc +export = plugin From 37ab09f3730000d565b7c064e51ed5abd7bf818a Mon Sep 17 00:00:00 2001 From: iamkun Date: Thu, 7 Mar 2019 18:45:08 +0800 Subject: [PATCH 13/22] chore: Add locale --- src/plugin/badMutable/index.js | 7 +++++++ test/plugin/badMutable.test.js | 13 +++++++++++++ 2 files changed, 20 insertions(+) diff --git a/src/plugin/badMutable/index.js b/src/plugin/badMutable/index.js index d8c362400..6d28124b4 100644 --- a/src/plugin/badMutable/index.js +++ b/src/plugin/badMutable/index.js @@ -22,5 +22,12 @@ export default (o, c) => { // locale needed later this.init() return this } + + const oldLocale = proto.locale + proto.locale = function (preset, object) { + if (!preset) return this.$L + this.$L = oldLocale.bind(this)(preset, object).$L + return this + } } diff --git a/test/plugin/badMutable.test.js b/test/plugin/badMutable.test.js index e2413df84..be9333251 100644 --- a/test/plugin/badMutable.test.js +++ b/test/plugin/badMutable.test.js @@ -2,6 +2,7 @@ import MockDate from 'mockdate' import moment from 'moment' import dayjs from '../../src' import badMutable from '../../src/plugin/badMutable' +import '../../src/locale/zh-cn' dayjs.extend(badMutable) @@ -148,3 +149,15 @@ it('daysInMonth', () => { expect(d.daysInMonth()).toBe(m.daysInMonth()) expect(d.format()).toBe(m.format()) }) + +it('Locale', () => { + const d = dayjs() + const m = moment() + const format = 'MMMM' + expect(d.locale()).toBe(m.locale()) + expect(d.format(format)).toBe(m.format(format)) + d.locale('zh-cn') + m.locale('zh-cn') + expect(d.locale()).toBe(m.locale()) + expect(d.format(format)).toBe(m.format(format)) +}) From c9916fe839ff637aa74d44baaef6616ad50fc818 Mon Sep 17 00:00:00 2001 From: iamkun Date: Thu, 7 Mar 2019 19:11:01 +0800 Subject: [PATCH 14/22] test: add more test --- src/index.js | 3 +-- src/plugin/badMutable/index.js | 20 ++++++++++++++++++++ test/plugin/badMutable.test.js | 11 +++++++++++ 3 files changed, 32 insertions(+), 2 deletions(-) diff --git a/src/index.js b/src/index.js index a80fcd3ac..ffdbe9671 100644 --- a/src/index.js +++ b/src/index.js @@ -344,8 +344,7 @@ class Dayjs { } daysInMonth() { - // clone is for badMutable plugin - return this.clone().endOf(C.M).$D + return this.endOf(C.M).$D } $locale() { // get locale object diff --git a/src/plugin/badMutable/index.js b/src/plugin/badMutable/index.js index 6d28124b4..f95d581c6 100644 --- a/src/plugin/badMutable/index.js +++ b/src/plugin/badMutable/index.js @@ -29,5 +29,25 @@ export default (o, c) => { // locale needed later this.$L = oldLocale.bind(this)(preset, object).$L return this } + + const oldDaysInMonth = proto.daysInMonth + proto.daysInMonth = function () { + return oldDaysInMonth.bind(this.clone())() + } + + const oldIsSame = proto.isSame + proto.isSame = function () { + return oldIsSame.bind(this.clone())() + } + + const oldIsBefore = proto.isBefore + proto.isBefore = function () { + return oldIsBefore.bind(this.clone())() + } + + const oldIsAfter = proto.isAfter + proto.isAfter = function () { + return oldIsAfter.bind(this.clone())() + } } diff --git a/test/plugin/badMutable.test.js b/test/plugin/badMutable.test.js index be9333251..e68128914 100644 --- a/test/plugin/badMutable.test.js +++ b/test/plugin/badMutable.test.js @@ -161,3 +161,14 @@ it('Locale', () => { expect(d.locale()).toBe(m.locale()) expect(d.format(format)).toBe(m.format(format)) }) + +it('isAfter isBefore isSame', () => { + const d = dayjs() + const format = dayjs().format() + d.isSame(dayjs, 'year') + expect(d.format()).toBe(format) + d.isBefore(dayjs, 'hour') + expect(d.format()).toBe(format) + d.isAfter(dayjs, 'month') + expect(d.format()).toBe(format) +}) From 8eb54047342fb282c02802a6decd0e98745a4727 Mon Sep 17 00:00:00 2001 From: iamkun Date: Thu, 7 Mar 2019 21:09:21 +0800 Subject: [PATCH 15/22] chore: Add localeData plugin --- src/plugin/localeData/index.js | 16 ++++++++++++++++ test/plugin/localeData.test.js | 26 ++++++++++++++++++++++++++ types/plugin/localeData.d.ts | 10 ++++++++++ 3 files changed, 52 insertions(+) create mode 100644 src/plugin/localeData/index.js create mode 100644 test/plugin/localeData.test.js create mode 100644 types/plugin/localeData.d.ts diff --git a/src/plugin/localeData/index.js b/src/plugin/localeData/index.js new file mode 100644 index 000000000..b85a838a4 --- /dev/null +++ b/src/plugin/localeData/index.js @@ -0,0 +1,16 @@ +export default (o, c) => { // locale needed later + const proto = c.prototype + const localeData = function () { + return { + months: instance => instance.format('MMMM'), + monthsShort: instance => instance.format('MMM'), + firstDayOfWeek: () => this.$locale().weekStart || 0, + weekdaysMin: instance => instance.format('dd'), + weekdaysShort: instance => instance.format('ddd') + } + } + proto.localeData = function () { + return localeData.bind(this)() + } +} + diff --git a/test/plugin/localeData.test.js b/test/plugin/localeData.test.js new file mode 100644 index 000000000..5e5e1cb95 --- /dev/null +++ b/test/plugin/localeData.test.js @@ -0,0 +1,26 @@ +import MockDate from 'mockdate' +import moment from 'moment' +import dayjs from '../../src' +import localeData from '../../src/plugin/localeData' + +dayjs.extend(localeData) + +beforeEach(() => { + MockDate.set(new Date()) +}) + +afterEach(() => { + MockDate.reset() +}) + +it('localeData', () => { + const d = dayjs() + const m = moment() + const dayjsLocaleData = dayjs().localeData() + const momentLocaleData = moment().localeData() + expect(dayjsLocaleData.firstDayOfWeek()).toBe(momentLocaleData.firstDayOfWeek()) + expect(dayjsLocaleData.months(d)).toBe(momentLocaleData.months(m)) + expect(dayjsLocaleData.monthsShort(d)).toBe(momentLocaleData.monthsShort(m)) + expect(dayjsLocaleData.weekdaysMin(d)).toBe(momentLocaleData.weekdaysMin(m)) + expect(dayjsLocaleData.weekdaysShort(d)).toBe(momentLocaleData.weekdaysShort(m)) +}) diff --git a/types/plugin/localeData.d.ts b/types/plugin/localeData.d.ts new file mode 100644 index 000000000..7d9817637 --- /dev/null +++ b/types/plugin/localeData.d.ts @@ -0,0 +1,10 @@ +import { PluginFunc } from 'dayjs' + +declare const plugin: PluginFunc +export = plugin + +declare module 'dayjs' { + interface Dayjs { + localeData(): any + } +} From 17683059ee991c7f32135d2d7b2c3f7630e6f052 Mon Sep 17 00:00:00 2001 From: iamkun Date: Thu, 7 Mar 2019 22:17:46 +0800 Subject: [PATCH 16/22] chore: Update isSame before after --- src/plugin/badMutable/index.js | 12 ++++++------ test/plugin/badMutable.test.js | 3 +++ 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/src/plugin/badMutable/index.js b/src/plugin/badMutable/index.js index f95d581c6..c82aafb67 100644 --- a/src/plugin/badMutable/index.js +++ b/src/plugin/badMutable/index.js @@ -36,18 +36,18 @@ export default (o, c) => { // locale needed later } const oldIsSame = proto.isSame - proto.isSame = function () { - return oldIsSame.bind(this.clone())() + proto.isSame = function (that, units) { + return oldIsSame.bind(this.clone())(that, units) } const oldIsBefore = proto.isBefore - proto.isBefore = function () { - return oldIsBefore.bind(this.clone())() + proto.isBefore = function (that, units) { + return oldIsBefore.bind(this.clone())(that, units) } const oldIsAfter = proto.isAfter - proto.isAfter = function () { - return oldIsAfter.bind(this.clone())() + proto.isAfter = function (that, units) { + return oldIsAfter.bind(this.clone())(that, units) } } diff --git a/test/plugin/badMutable.test.js b/test/plugin/badMutable.test.js index e68128914..5b38bc899 100644 --- a/test/plugin/badMutable.test.js +++ b/test/plugin/badMutable.test.js @@ -167,8 +167,11 @@ it('isAfter isBefore isSame', () => { const format = dayjs().format() d.isSame(dayjs, 'year') expect(d.format()).toBe(format) + expect(d.isSame()).toBe(true) d.isBefore(dayjs, 'hour') expect(d.format()).toBe(format) + expect(d.isBefore()).toBe(false) d.isAfter(dayjs, 'month') expect(d.format()).toBe(format) + expect(d.isAfter()).toBe(false) }) From bf27fda1e3292973eb54fe9699f2637b44efaefe Mon Sep 17 00:00:00 2001 From: iamkun Date: Sun, 10 Mar 2019 16:59:36 +0800 Subject: [PATCH 17/22] fix: CustomParseFormat plugin parse Do format string fix #522 --- src/plugin/customParseFormat/index.js | 12 +++++++++++- test/plugin/customParseFormat.test.js | 17 +++++++++++++++++ 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/src/plugin/customParseFormat/index.js b/src/plugin/customParseFormat/index.js index cffbffbbb..0851d4edd 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?M?M?|DD?|hh?|HH?|mm?|ss?|S{1,3}|z|ZZ?)/g +const formattingTokens = /(\[[^[]*\])|([-:/.()\s]+)|(A|a|YYYY|YY?|MM?M?M?|Do|DD?|hh?|HH?|mm?|ss?|S{1,3}|z|ZZ?)/g const match1 = /\d/ // 0 - 9 const match2 = /\d\d/ // 00 - 99 @@ -56,6 +56,16 @@ const expressions = { hh: [match1to2, addInput('hours')], D: [match1to2, addInput('day')], DD: [match2, addInput('day')], + Do: [matchWord, function (input) { + const { ordinal } = locale; + [this.day] = input.match(/\d+/) + if (!ordinal) return + for (let i = 1; i <= 31; i += 1) { + if (ordinal(i).replace(/\[|\]/g, '') === input) { + this.day = i + } + } + }], M: [match1to2, addInput('month')], MM: [match2, addInput('month')], MMM: [matchWord, function (input) { diff --git a/test/plugin/customParseFormat.test.js b/test/plugin/customParseFormat.test.js index eb2f2204b..46286bc66 100644 --- a/test/plugin/customParseFormat.test.js +++ b/test/plugin/customParseFormat.test.js @@ -3,6 +3,7 @@ import moment from 'moment' import dayjs from '../../src' import customParseFormat from '../../src/plugin/customParseFormat' import uk from '../../src/locale/uk' +import '../../src/locale/zh-cn' dayjs.extend(customParseFormat) @@ -169,3 +170,19 @@ it('correctly parse month from string after changing locale globally', () => { moment.locale(momentLocale) } }) + +it('correctly parse ordinal', () => { + const input = '7th March 2019' + const input2 = '17th March 2019' + const inputFalse = '7st March 2019' + const inputZHCN = '7日 三月 2019' + const format = 'Do MMMM YYYY' + expect(dayjs(input, format).valueOf()) + .toBe(moment(input, format).valueOf()) + expect(dayjs(input2, format).valueOf()) + .toBe(moment(input2, format).valueOf()) + expect(dayjs(inputFalse, format).valueOf()) + .toBe(moment(inputFalse, format).valueOf()) + expect(dayjs(inputZHCN, format, 'zh-cn').valueOf()) + .toBe(moment(inputZHCN, format, 'zh-cn').valueOf()) +}) From c46663227c66349515cf15c7ffb0d11ff3fe0659 Mon Sep 17 00:00:00 2001 From: iamkun Date: Sun, 10 Mar 2019 17:18:48 +0800 Subject: [PATCH 18/22] docs: Update docs --- docs/en/Plugin.md | 1 + docs/es-es/Plugin.md | 1 + docs/ja/Plugin.md | 1 + docs/ko/Plugin.md | 1 + docs/pt-br/Plugin.md | 1 + docs/zh-cn/Plugin.md | 1 + 6 files changed, 6 insertions(+) diff --git a/docs/en/Plugin.md b/docs/en/Plugin.md index 87b1cb9db..bddd23bdf 100644 --- a/docs/en/Plugin.md +++ b/docs/en/Plugin.md @@ -339,6 +339,7 @@ dayjs('2018 Enero 15', 'YYYY MMMM DD', 'es') | `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 | +| `Do` | 1st... 31st | Day of Month with ordinal | ### ToArray diff --git a/docs/es-es/Plugin.md b/docs/es-es/Plugin.md index 4764cefb4..9d30c29f1 100644 --- a/docs/es-es/Plugin.md +++ b/docs/es-es/Plugin.md @@ -339,6 +339,7 @@ dayjs('2018 Enero 15', 'YYYY MMMM DD', 'es') | `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 | +| `Do` | 1st... 31st | Día del mes con ordinal | ### ToArray diff --git a/docs/ja/Plugin.md b/docs/ja/Plugin.md index 83cfaaf7d..db28bcc58 100644 --- a/docs/ja/Plugin.md +++ b/docs/ja/Plugin.md @@ -348,6 +348,7 @@ dayjs('2018 5月 15', 'YYYY MMMM DD', 'ja') | `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 | +| `Do` | 1st... 31st | 序数付きの日 | ### ToArray diff --git a/docs/ko/Plugin.md b/docs/ko/Plugin.md index 267be0ce1..af6f11016 100644 --- a/docs/ko/Plugin.md +++ b/docs/ko/Plugin.md @@ -340,6 +340,7 @@ dayjs('2018 5월 15', 'YYYY MMMM DD', 'ko') | `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 | +| `Do` | 1st... 31st | 서수형식의 일자 명 | ### ToArray diff --git a/docs/pt-br/Plugin.md b/docs/pt-br/Plugin.md index ae5f29d99..2fa6af1b5 100644 --- a/docs/pt-br/Plugin.md +++ b/docs/pt-br/Plugin.md @@ -339,6 +339,7 @@ dayjs('2018 Fevereiro 15', 'YYYY MMMM DD', 'pt_br') | `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 | +| `Do` | 1st... 31st | Dia do mês com ordinal | ### ToArray diff --git a/docs/zh-cn/Plugin.md b/docs/zh-cn/Plugin.md index 909038ee6..c5c0ae2b3 100644 --- a/docs/zh-cn/Plugin.md +++ b/docs/zh-cn/Plugin.md @@ -338,6 +338,7 @@ dayjs('2018 五月 15', 'YYYY MMMM DD', 'zh_cn') | `ZZ` | +0500 | UTC 的偏移量,数字前面加上 0 | | `A` | AM PM | | | `a` | am pm | | +| `Do` | 1st... 31st | 带序号的月份 | ### ToArray From 1ddf633ca8a4456af028bec1fa7f2ba0bdcb9537 Mon Sep 17 00:00:00 2001 From: iamkun Date: Sun, 10 Mar 2019 18:06:21 +0800 Subject: [PATCH 19/22] chore: Update weekOfYear --- src/plugin/weekOfYear/index.js | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/plugin/weekOfYear/index.js b/src/plugin/weekOfYear/index.js index b7c301361..e2fc9b3e8 100644 --- a/src/plugin/weekOfYear/index.js +++ b/src/plugin/weekOfYear/index.js @@ -6,11 +6,12 @@ export default (o, c, d) => { if (week !== null) { return this.add((week - this.week()) * 7, 'day') } - const endOfYear = this.endOf(Y) + // d(this) clone is for badMutable plugin + const endOfYear = d(this).endOf(Y) if (endOfYear.day() !== 6 && this.month() === 11 && (31 - this.date()) <= endOfYear.day()) { return 1 } - const startOfYear = d(this.$d).startOf(Y) + const startOfYear = d(this).startOf(Y) const compareDay = startOfYear.subtract(startOfYear.day(), D).subtract(1, MS) const diffInWeek = this.diff(compareDay, W, true) return Math.ceil(diffInWeek) From 6981ab6decd8556d6c43042eb3ad88a6ee4151f7 Mon Sep 17 00:00:00 2001 From: iamkun Date: Sun, 10 Mar 2019 18:13:47 +0800 Subject: [PATCH 20/22] chore: Update AdvancedFormat plugin support wo format string fro week of the year --- src/locale/zh-cn.js | 10 +++++++++- src/plugin/advancedFormat/index.js | 7 ++++--- test/plugin/advancedFormat.test.js | 10 ++++++++++ 3 files changed, 23 insertions(+), 4 deletions(-) diff --git a/src/locale/zh-cn.js b/src/locale/zh-cn.js index bc28c7edf..83b92acd4 100644 --- a/src/locale/zh-cn.js +++ b/src/locale/zh-cn.js @@ -7,7 +7,15 @@ const locale = { weekdaysMin: '日_一_二_三_四_五_六'.split('_'), months: '一月_二月_三月_四月_五月_六月_七月_八月_九月_十月_十一月_十二月'.split('_'), monthsShort: '1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月'.split('_'), - ordinal: n => `${n}日`, + ordinal1: n => `${n}日`, + ordinal: (number, period) => { + switch (period) { + case 'W': + return `${number}周` + default: + return `${number}日` + } + }, weekStart: 1, formats: { LT: 'HH:mm', diff --git a/src/plugin/advancedFormat/index.js b/src/plugin/advancedFormat/index.js index 854f2b73b..9a1e30eb2 100644 --- a/src/plugin/advancedFormat/index.js +++ b/src/plugin/advancedFormat/index.js @@ -13,13 +13,14 @@ export default (o, c, d) => { // locale needed later const locale = this.$locale() const utils = this.$utils() const str = formatStr || FORMAT_DEFAULT - const result = str.replace(/Q|Do|X|x|k{1,2}|S/g, (match) => { + const result = str.replace(/Q|wo|Do|X|x|k{1,2}|S/g, (match) => { switch (match) { case 'Q': return Math.ceil((this.$M + 1) / 3) - case 'Do': { + case 'Do': return locale.ordinal(this.$D) - } + case 'wo': + return locale.ordinal(this.week(), 'W') // W for week case 'k': case 'kk': return utils.s(String(this.$H === 0 ? 24 : this.$H), match === 'k' ? 1 : 2, '0') diff --git a/test/plugin/advancedFormat.test.js b/test/plugin/advancedFormat.test.js index 985ff50be..37c185576 100644 --- a/test/plugin/advancedFormat.test.js +++ b/test/plugin/advancedFormat.test.js @@ -2,7 +2,10 @@ import MockDate from 'mockdate' import moment from 'moment' import dayjs from '../../src' import advancedFormat from '../../src/plugin/advancedFormat' +import weekOfYear from '../../src/plugin/weekOfYear' +import '../../src/locale/zh-cn' +dayjs.extend(weekOfYear) dayjs.extend(advancedFormat) beforeEach(() => { @@ -65,3 +68,10 @@ it('Format Hour k kk 24-hour 1 - 24', () => { expect(dayjs(d).format('kk')).toBe('23') expect(dayjs(d).format('kk')).toBe(moment(d).format('kk')) }) + +it('Format Week of Year wo', () => { + const d = '2018-12-01' + expect(dayjs(d).format('wo')).toBe(moment(d).format('wo')) + expect(dayjs(d).locale('zh-cn').format('wo')) + .toBe(moment(d).locale('zh-cn').format('wo')) +}) From a8926082ee11979866e1328214443ae1823f5f07 Mon Sep 17 00:00:00 2001 From: iamkun Date: Sun, 10 Mar 2019 18:32:14 +0800 Subject: [PATCH 21/22] fix: Add WeekYear plugin --- src/locale/zh-cn.js | 1 - src/plugin/weekYear/index.js | 12 ++++++++++++ test/plugin/weekYear.test.js | 30 ++++++++++++++++++++++++++++++ types/plugin/weekOfYear.d.ts | 2 ++ types/plugin/weekYear.d.ts | 10 ++++++++++ 5 files changed, 54 insertions(+), 1 deletion(-) create mode 100644 src/plugin/weekYear/index.js create mode 100644 test/plugin/weekYear.test.js create mode 100644 types/plugin/weekYear.d.ts diff --git a/src/locale/zh-cn.js b/src/locale/zh-cn.js index 83b92acd4..e3e754432 100644 --- a/src/locale/zh-cn.js +++ b/src/locale/zh-cn.js @@ -7,7 +7,6 @@ const locale = { weekdaysMin: '日_一_二_三_四_五_六'.split('_'), months: '一月_二月_三月_四月_五月_六月_七月_八月_九月_十月_十一月_十二月'.split('_'), monthsShort: '1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月'.split('_'), - ordinal1: n => `${n}日`, ordinal: (number, period) => { switch (period) { case 'W': diff --git a/src/plugin/weekYear/index.js b/src/plugin/weekYear/index.js new file mode 100644 index 000000000..1fa7577b7 --- /dev/null +++ b/src/plugin/weekYear/index.js @@ -0,0 +1,12 @@ +export default (o, c) => { + const proto = c.prototype + proto.weekYear = function () { + const month = this.month() + const weekOfYear = this.week() + const year = this.year() + if (weekOfYear === 1 && month === 11) { + return year + 1 + } + return year + } +} diff --git a/test/plugin/weekYear.test.js b/test/plugin/weekYear.test.js new file mode 100644 index 000000000..a23709e50 --- /dev/null +++ b/test/plugin/weekYear.test.js @@ -0,0 +1,30 @@ +import moment from 'moment' +import MockDate from 'mockdate' +import dayjs from '../../src' +import weekYear from '../../src/plugin/weekYear' +import weekOfYear from '../../src/plugin/weekOfYear' + +dayjs.extend(weekYear) +dayjs.extend(weekOfYear) + +beforeEach(() => { + MockDate.set(new Date()) +}) + +afterEach(() => { + MockDate.reset() +}) + +it('Week Year', () => { + const daySet = [ + ['2018-12-01', 2018], + ['2018-12-30', 2019], + ['2018-12-31', 2019], + ['2019-01-01', 2019] + ] + daySet.forEach((d) => { + const [day, result] = d + expect(dayjs(day).weekYear()).toBe(result) + expect(dayjs(day).weekYear()).toBe(moment(day).weekYear()) + }) +}) diff --git a/types/plugin/weekOfYear.d.ts b/types/plugin/weekOfYear.d.ts index 360219556..d98801455 100644 --- a/types/plugin/weekOfYear.d.ts +++ b/types/plugin/weekOfYear.d.ts @@ -6,5 +6,7 @@ export = plugin declare module 'dayjs' { interface Dayjs { week(): number + + week(value : number): Dayjs } } diff --git a/types/plugin/weekYear.d.ts b/types/plugin/weekYear.d.ts new file mode 100644 index 000000000..df2533123 --- /dev/null +++ b/types/plugin/weekYear.d.ts @@ -0,0 +1,10 @@ +import { PluginFunc } from 'dayjs' + +declare const plugin: PluginFunc +export = plugin + +declare module 'dayjs' { + interface Dayjs { + weekYear(): number + } +} From 0fc23979095e96aa5ed7279fedce0c8325472b31 Mon Sep 17 00:00:00 2001 From: iamkun Date: Sun, 10 Mar 2019 18:36:08 +0800 Subject: [PATCH 22/22] chore: Update AdvancedFormat plugin parse gggg for week year --- src/plugin/advancedFormat/index.js | 4 +++- test/plugin/advancedFormat.test.js | 7 +++++++ 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/src/plugin/advancedFormat/index.js b/src/plugin/advancedFormat/index.js index 9a1e30eb2..1b5288c08 100644 --- a/src/plugin/advancedFormat/index.js +++ b/src/plugin/advancedFormat/index.js @@ -13,12 +13,14 @@ export default (o, c, d) => { // locale needed later const locale = this.$locale() const utils = this.$utils() const str = formatStr || FORMAT_DEFAULT - const result = str.replace(/Q|wo|Do|X|x|k{1,2}|S/g, (match) => { + const result = str.replace(/Q|wo|gggg|Do|X|x|k{1,2}|S/g, (match) => { switch (match) { case 'Q': return Math.ceil((this.$M + 1) / 3) case 'Do': return locale.ordinal(this.$D) + case 'gggg': + return this.weekYear() case 'wo': return locale.ordinal(this.week(), 'W') // W for week case 'k': diff --git a/test/plugin/advancedFormat.test.js b/test/plugin/advancedFormat.test.js index 37c185576..74de4eb9b 100644 --- a/test/plugin/advancedFormat.test.js +++ b/test/plugin/advancedFormat.test.js @@ -3,8 +3,10 @@ import moment from 'moment' import dayjs from '../../src' import advancedFormat from '../../src/plugin/advancedFormat' import weekOfYear from '../../src/plugin/weekOfYear' +import weekYear from '../../src/plugin/weekYear' import '../../src/locale/zh-cn' +dayjs.extend(weekYear) dayjs.extend(weekOfYear) dayjs.extend(advancedFormat) @@ -75,3 +77,8 @@ it('Format Week of Year wo', () => { expect(dayjs(d).locale('zh-cn').format('wo')) .toBe(moment(d).locale('zh-cn').format('wo')) }) + +it('Format Week Year gggg', () => { + const d = '2018-12-31' + expect(dayjs(d).format('gggg')).toBe(moment(d).format('gggg')) +})