Skip to content

Commit

Permalink
feat(useDateFormat): support dd, ddd and dddd formatter (#1986)
Browse files Browse the repository at this point in the history
Co-authored-by: webfansplz <308241863@qq.com>
  • Loading branch information
aki77 and webfansplz committed Jul 29, 2022
1 parent 0f79145 commit 5b1e005
Show file tree
Hide file tree
Showing 3 changed files with 65 additions and 21 deletions.
22 changes: 22 additions & 0 deletions packages/shared/useDateFormat/index.md
Expand Up @@ -26,9 +26,14 @@ Get the formatted date according to the string of tokens passed in, inspired by
| `ss` | 00-59 | The second, 2-digits |
| `SSS` | 000-999 | The millisecond, 3-digits |
| `d` | 0-6 | The day of the week, with Sunday as 0 |
| `dd` | S-S | The min name of the day of the week |
| `ddd` | Sun-Sat | The short name of the day of the week |
| `dddd` | Sunday-Saturday | The name of the day of the week |

## Usage

### Basic

```html
<script setup lang="ts">
Expand All @@ -43,3 +48,20 @@ const formatted = useDateFormat(useNow(), 'YYYY-MM-DD HH:mm:ss')
<div>{{ formatted }}</div>
</template>
```

### Use with locale

```html
<script setup lang="ts">
import { ref, computed } from 'vue-demi'
import { useNow, useDateFormat } from '@vueuse/core'
const formatted = useDateFormat(useNow(), 'YYYY-MM-DD (ddd)', { locales: 'en-US' })
</script>

<template>
<div>{{ formatted }}</div>
</template>
```
9 changes: 9 additions & 0 deletions packages/shared/useDateFormat/index.test.ts
Expand Up @@ -28,4 +28,13 @@ describe('useDateFormat', () => {
it('should work with HH:mm:ss d', () => {
expect(useDateFormat(new Date('2022-01-01 15:05:05'), 'HH:mm:ss d').value).toBe('15:05:05 6')
})
it('should work with YYYY/MM/DD dd', () => {
expect(useDateFormat(new Date('2022-01-01 15:05:05'), 'YYYY/MM/DD dd', { locales: 'en-US' }).value).toBe('2022/01/01 S')
})
it('should work with YYYY/MM/DD ddd', () => {
expect(useDateFormat(new Date('2022-01-01 15:05:05'), 'YYYY/MM/DD ddd', { locales: 'en-US' }).value).toBe('2022/01/01 Sat')
})
it('should work with YYYY/MM/DD dddd', () => {
expect(useDateFormat(new Date('2022-01-01 15:05:05'), 'YYYY/MM/DD dddd', { locales: 'en-US' }).value).toBe('2022/01/01 Saturday')
})
})
55 changes: 34 additions & 21 deletions packages/shared/useDateFormat/index.ts
Expand Up @@ -4,10 +4,19 @@ import { computed } from 'vue-demi'

export type DateLike = Date | number | string | undefined

export interface UseDateFormatOptions {
/**
* The locale(s) to used for dd/ddd/dddd format
*
* [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl#locales_argument).
*/
locales?: Intl.LocalesArgument
}

const REGEX_PARSE = /* #__PURE__ */ /^(\d{4})[-/]?(\d{1,2})?[-/]?(\d{0,2})[Tt\s]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?[.:]?(\d+)?$/
const REGEX_FORMAT = /* #__PURE__ */ /\[([^\]]+)]|Y{1,4}|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a|A|m{1,2}|s{1,2}|Z{1,2}|SSS/g

export const formatDate = (date: Date, formatStr: string) => {
export const formatDate = (date: Date, formatStr: string, locales?: Intl.LocalesArgument) => {
const years = date.getFullYear()
const month = date.getMonth()
const days = date.getDate()
Expand All @@ -16,25 +25,28 @@ export const formatDate = (date: Date, formatStr: string) => {
const seconds = date.getSeconds()
const milliseconds = date.getMilliseconds()
const day = date.getDay()
const matches: Record<string, string | number> = {
YY: String(years).slice(-2),
YYYY: years,
M: month + 1,
MM: `${month + 1}`.padStart(2, '0'),
D: String(days),
DD: `${days}`.padStart(2, '0'),
H: String(hours),
HH: `${hours}`.padStart(2, '0'),
h: `${hours % 12 || 12}`.padStart(1, '0'),
hh: `${hours % 12 || 12}`.padStart(2, '0'),
m: String(minutes),
mm: `${minutes}`.padStart(2, '0'),
s: String(seconds),
ss: `${seconds}`.padStart(2, '0'),
SSS: `${milliseconds}`.padStart(3, '0'),
d: day,
const matches: Record<string, () => string | number> = {
YY: () => String(years).slice(-2),
YYYY: () => years,
M: () => month + 1,
MM: () => `${month + 1}`.padStart(2, '0'),
D: () => String(days),
DD: () => `${days}`.padStart(2, '0'),
H: () => String(hours),
HH: () => `${hours}`.padStart(2, '0'),
h: () => `${hours % 12 || 12}`.padStart(1, '0'),
hh: () => `${hours % 12 || 12}`.padStart(2, '0'),
m: () => String(minutes),
mm: () => `${minutes}`.padStart(2, '0'),
s: () => String(seconds),
ss: () => `${seconds}`.padStart(2, '0'),
SSS: () => `${milliseconds}`.padStart(3, '0'),
d: () => day,
dd: () => date.toLocaleDateString(locales, { weekday: 'narrow' }),
ddd: () => date.toLocaleDateString(locales, { weekday: 'short' }),
dddd: () => date.toLocaleDateString(locales, { weekday: 'long' }),
}
return formatStr.replace(REGEX_FORMAT, (match, $1) => $1 || matches[match])
return formatStr.replace(REGEX_FORMAT, (match, $1) => $1 || matches[match]())
}

export const normalizeDate = (date: DateLike) => {
Expand Down Expand Up @@ -63,10 +75,11 @@ export const normalizeDate = (date: DateLike) => {
* @see https://vueuse.org/useDateFormat
* @param date
* @param formatStr
* @param options
*/

export function useDateFormat(date: MaybeComputedRef<DateLike>, formatStr: MaybeComputedRef<string> = 'HH:mm:ss') {
return computed(() => formatDate(normalizeDate(resolveUnref(date)), resolveUnref(formatStr)))
export function useDateFormat(date: MaybeComputedRef<DateLike>, formatStr: MaybeComputedRef<string> = 'HH:mm:ss', options: UseDateFormatOptions = {}) {
return computed(() => formatDate(normalizeDate(resolveUnref(date)), resolveUnref(formatStr), options?.locales))
}

export type UseDateFormatReturn = ReturnType<typeof useDateFormat>

0 comments on commit 5b1e005

Please sign in to comment.