Skip to content

Commit

Permalink
perf: speed up date formatting
Browse files Browse the repository at this point in the history
  • Loading branch information
kevcodez committed Sep 14, 2021
1 parent e0d9336 commit 65f9ba8
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 4 deletions.
28 changes: 28 additions & 0 deletions bench.js
Original file line number Diff line number Diff line change
Expand Up @@ -50,22 +50,38 @@ const arraySchemaCJS = {
items: schemaCJS
}

const dateFormatSchema = {
description: 'Date of birth',
type: 'string',
format: 'date'
}

const dateFormatSchemaCJS = {
description: 'Date of birth',
type: 'string',
format: 'date'
}

const obj = {
firstName: 'Matteo',
lastName: 'Collina',
age: 32
}

const date = new Date()

const multiArray = []

const CJS = require('compile-json-stringify')
const CJSStringify = CJS(schemaCJS)
const CJSStringifyArray = CJS(arraySchemaCJS)
const CJSStringifyDate = CJS(dateFormatSchemaCJS)
const CJSStringifyString = CJS({ type: 'string' })

const FJS = require('.')
const stringify = FJS(schema)
const stringifyArray = FJS(arraySchema)
const stringifyDate = FJS(dateFormatSchema)
const stringifyString = FJS({ type: 'string' })
let str = ''

Expand Down Expand Up @@ -138,6 +154,18 @@ suite.add('compile-json-stringify obj', function () {
CJSStringify(obj)
})

suite.add('JSON stringify date', function () {
JSON.stringify(date)
})

suite.add('fast-json-stringify date format', function () {
stringifyDate(date)
})

suite.add('compile-json-stringify date format', function () {
CJSStringifyDate(date)
})

suite.on('cycle', cycle)

suite.run()
Expand Down
5 changes: 1 addition & 4 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -285,10 +285,7 @@ function $asDatetime (date, skipQuotes) {
function $asDate (date, skipQuotes) {
const quotes = skipQuotes === true ? '' : '"'
if (date instanceof Date) {
const year = new Intl.DateTimeFormat('en', { year: 'numeric' }).format(date)
const month = new Intl.DateTimeFormat('en', { month: '2-digit' }).format(date)
const day = new Intl.DateTimeFormat('en', { day: '2-digit' }).format(date)
return quotes + year + '-' + month + '-' + day + quotes
return quotes + new Date(date.getTime() - (date.getTimezoneOffset() * 60000 )).toISOString().slice(0, 10) + quotes
} else if (date && typeof date.format === 'function') {
return quotes + date.format('YYYY-MM-DD') + quotes
} else {
Expand Down

0 comments on commit 65f9ba8

Please sign in to comment.