diff --git a/docs/en/API-reference.md b/docs/en/API-reference.md index 54ee2a3b6..53102fec1 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 @@ -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)` @@ -354,14 +362,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 +378,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 +477,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..bddd23bdf 100644 --- a/docs/en/Plugin.md +++ b/docs/en/Plugin.md @@ -339,6 +339,38 @@ 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 + +- 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 diff --git a/docs/es-es/API-reference.md b/docs/es-es/API-reference.md index b165afcc3..d26c925a4 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 @@ -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)` @@ -354,14 +362,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 +378,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 +477,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..9d30c29f1 100644 --- a/docs/es-es/Plugin.md +++ b/docs/es-es/Plugin.md @@ -339,6 +339,38 @@ 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 + +- 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 diff --git a/docs/ja/API-reference.md b/docs/ja/API-reference.md index 57357a0da..57daefcbe 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) --- @@ -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 @@ -408,16 +400,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 +420,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 +533,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..db28bcc58 100644 --- a/docs/ja/Plugin.md +++ b/docs/ja/Plugin.md @@ -348,6 +348,38 @@ 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 + +- 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 } */ +``` ## カスタマイズ diff --git a/docs/ko/API-reference.md b/docs/ko/API-reference.md index 62bcf83d0..01fa80488 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 @@ -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)` @@ -353,14 +361,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 +377,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 +476,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..af6f11016 100644 --- a/docs/ko/Plugin.md +++ b/docs/ko/Plugin.md @@ -340,6 +340,38 @@ 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 + +- 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 diff --git a/docs/pt-br/API-reference.md b/docs/pt-br/API-reference.md index baa9857d7..2213127c4 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 @@ -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)` @@ -352,14 +360,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 +376,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 +475,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..2fa6af1b5 100644 --- a/docs/pt-br/Plugin.md +++ b/docs/pt-br/Plugin.md @@ -339,6 +339,38 @@ 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 + +- 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 diff --git a/docs/zh-cn/API-reference.md b/docs/zh-cn/API-reference.md index 468fa65ee..aa96f2891 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 @@ - [是否相同或之前](#是否相同或之前) - [是否之间](#是否之间) - [年中第几季度](#年中第几季度) + - [转成数组](#转成数组) + - [转成对象](#转成对象) --- @@ -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) ``` #### 设置 @@ -406,16 +398,6 @@ dayjs().daysInMonth() dayjs().toDate() ``` -#### 数组 - -- return Array - -返回包含时间数值的数组。 - -```js -dayjs().toArray() //[2018, 8, 18, 00, 00, 00, 000]; -``` - #### As JSON - return JSON String @@ -436,16 +418,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 +509,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..c5c0ae2b3 100644 --- a/docs/zh-cn/Plugin.md +++ b/docs/zh-cn/Plugin.md @@ -338,6 +338,38 @@ dayjs('2018 五月 15', 'YYYY MMMM DD', 'zh_cn') | `ZZ` | +0500 | UTC 的偏移量,数字前面加上 0 | | `A` | AM PM | | | `a` | am pm | | +| `Do` | 1st... 31st | 带序号的月份 | + +### 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 } */ +``` ## 自定义 diff --git a/src/index.js b/src/index.js index 4f96f9c91..ffdbe9671 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() { @@ -227,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) => { @@ -346,6 +352,7 @@ class Dayjs { } locale(preset, object) { + if (!preset) return this.$L const that = this.clone() that.$L = parseLocale(preset, object, true) return that @@ -359,18 +366,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() } @@ -382,18 +377,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/locale/zh-cn.js b/src/locale/zh-cn.js index bc28c7edf..e3e754432 100644 --- a/src/locale/zh-cn.js +++ b/src/locale/zh-cn.js @@ -7,7 +7,14 @@ const locale = { weekdaysMin: '日_一_二_三_四_五_六'.split('_'), months: '一月_二月_三月_四月_五月_六月_七月_八月_九月_十月_十一月_十二月'.split('_'), monthsShort: '1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月'.split('_'), - ordinal: 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..1b5288c08 100644 --- a/src/plugin/advancedFormat/index.js +++ b/src/plugin/advancedFormat/index.js @@ -13,13 +13,16 @@ 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|gggg|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 'gggg': + return this.weekYear() + 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/src/plugin/badMutable/index.js b/src/plugin/badMutable/index.js new file mode 100644 index 000000000..c82aafb67 --- /dev/null +++ b/src/plugin/badMutable/index.js @@ -0,0 +1,53 @@ +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 + } + + const oldLocale = proto.locale + proto.locale = function (preset, object) { + if (!preset) return this.$L + 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 (that, units) { + return oldIsSame.bind(this.clone())(that, units) + } + + const oldIsBefore = proto.isBefore + proto.isBefore = function (that, units) { + return oldIsBefore.bind(this.clone())(that, units) + } + + const oldIsAfter = proto.isAfter + proto.isAfter = function (that, units) { + return oldIsAfter.bind(this.clone())(that, units) + } +} + 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/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/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/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/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) 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/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/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', () => { 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/test/plugin/advancedFormat.test.js b/test/plugin/advancedFormat.test.js index 985ff50be..74de4eb9b 100644 --- a/test/plugin/advancedFormat.test.js +++ b/test/plugin/advancedFormat.test.js @@ -2,7 +2,12 @@ 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 weekYear from '../../src/plugin/weekYear' +import '../../src/locale/zh-cn' +dayjs.extend(weekYear) +dayjs.extend(weekOfYear) dayjs.extend(advancedFormat) beforeEach(() => { @@ -65,3 +70,15 @@ 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')) +}) + +it('Format Week Year gggg', () => { + const d = '2018-12-31' + expect(dayjs(d).format('gggg')).toBe(moment(d).format('gggg')) +}) diff --git a/test/plugin/badMutable.test.js b/test/plugin/badMutable.test.js new file mode 100644 index 000000000..5b38bc899 --- /dev/null +++ b/test/plugin/badMutable.test.js @@ -0,0 +1,177 @@ +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) + +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()) +}) + +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)) +}) + +it('isAfter isBefore isSame', () => { + const d = dayjs() + 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) +}) 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()) +}) 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/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/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()) +}) 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/index.d.ts b/types/index.d.ts index 22ea11726..eee848e61 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) @@ -31,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 @@ -67,14 +73,10 @@ declare namespace dayjs { toDate(): Date - toArray(): number[] - toJSON(): string toISOString(): string - toObject(): DayjsObject - toString(): string utcOffset(): number @@ -85,6 +87,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 } 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 diff --git a/types/plugin/isMoment.d.ts b/types/plugin/isMoment.d.ts new file mode 100644 index 000000000..dac24f6f7 --- /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 isMoment(input: any): boolean + +} 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 + } +} 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 + } +} 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 + } +}