Skip to content

Commit ffed186

Browse files
authored
perf: speed up date formatting (#357)
1 parent e0d9336 commit ffed186

File tree

2 files changed

+29
-4
lines changed

2 files changed

+29
-4
lines changed

bench.js

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,22 +50,38 @@ const arraySchemaCJS = {
5050
items: schemaCJS
5151
}
5252

53+
const dateFormatSchema = {
54+
description: 'Date of birth',
55+
type: 'string',
56+
format: 'date'
57+
}
58+
59+
const dateFormatSchemaCJS = {
60+
description: 'Date of birth',
61+
type: 'string',
62+
format: 'date'
63+
}
64+
5365
const obj = {
5466
firstName: 'Matteo',
5567
lastName: 'Collina',
5668
age: 32
5769
}
5870

71+
const date = new Date()
72+
5973
const multiArray = []
6074

6175
const CJS = require('compile-json-stringify')
6276
const CJSStringify = CJS(schemaCJS)
6377
const CJSStringifyArray = CJS(arraySchemaCJS)
78+
const CJSStringifyDate = CJS(dateFormatSchemaCJS)
6479
const CJSStringifyString = CJS({ type: 'string' })
6580

6681
const FJS = require('.')
6782
const stringify = FJS(schema)
6883
const stringifyArray = FJS(arraySchema)
84+
const stringifyDate = FJS(dateFormatSchema)
6985
const stringifyString = FJS({ type: 'string' })
7086
let str = ''
7187

@@ -138,6 +154,18 @@ suite.add('compile-json-stringify obj', function () {
138154
CJSStringify(obj)
139155
})
140156

157+
suite.add('JSON stringify date', function () {
158+
JSON.stringify(date)
159+
})
160+
161+
suite.add('fast-json-stringify date format', function () {
162+
stringifyDate(date)
163+
})
164+
165+
suite.add('compile-json-stringify date format', function () {
166+
CJSStringifyDate(date)
167+
})
168+
141169
suite.on('cycle', cycle)
142170

143171
suite.run()

index.js

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -285,10 +285,7 @@ function $asDatetime (date, skipQuotes) {
285285
function $asDate (date, skipQuotes) {
286286
const quotes = skipQuotes === true ? '' : '"'
287287
if (date instanceof Date) {
288-
const year = new Intl.DateTimeFormat('en', { year: 'numeric' }).format(date)
289-
const month = new Intl.DateTimeFormat('en', { month: '2-digit' }).format(date)
290-
const day = new Intl.DateTimeFormat('en', { day: '2-digit' }).format(date)
291-
return quotes + year + '-' + month + '-' + day + quotes
288+
return quotes + new Date(date.getTime() - (date.getTimezoneOffset() * 60000 )).toISOString().slice(0, 10) + quotes
292289
} else if (date && typeof date.format === 'function') {
293290
return quotes + date.format('YYYY-MM-DD') + quotes
294291
} else {

0 commit comments

Comments
 (0)