Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(useDateFormat): support dd, ddd and dddd formatter #1986

Merged
merged 2 commits into from Jul 29, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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> = {
webfansplz marked this conversation as resolved.
Show resolved Hide resolved
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>