Skip to content
This repository has been archived by the owner on Jul 17, 2023. It is now read-only.

Commit

Permalink
improve timezone offset performance
Browse files Browse the repository at this point in the history
  • Loading branch information
SerayaEryn committed Aug 23, 2018
1 parent 489d3d9 commit c79b9d3
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 4 deletions.
11 changes: 7 additions & 4 deletions DateFormatter.js
Expand Up @@ -33,8 +33,11 @@ DateFormatter.prototype.format = function format(dateFormat, date) {

function buildFormatter(dateFormat) {
var tokens = tokenizer.tokenize(dateFormat);
var functionString = 'return `' + tokens.map(processToken).join('') + '`';

var functionString = '';
if (tokens.includes('Z') || tokens.includes('ZZ')) {
functionString += 'var offset = now.getTimezoneOffset();\n';
}
functionString += 'return `' + tokens.map(processToken).join('') + '`';
return Function(
'now',
'padZero2',
Expand All @@ -50,8 +53,8 @@ function buildFormatter(dateFormat) {
}

var tokenToReplacement = {
ZZ: '${now.getTimezoneOffset() >= 0 ? \'-\':\'+\'}${padZero2(Math.abs(~~(now.getTimezoneOffset() / 60)))}:${padZero2(now.getTimezoneOffset() % 60)}',
Z: '${now.getTimezoneOffset() >= 0 ? \'-\':\'+\'}${padZero2(Math.abs(~~(now.getTimezoneOffset() / 60)))}${padZero2(now.getTimezoneOffset() % 60)}',
ZZ: '${offset >= 0 ? \'-\':\'+\'}${padZero2(Math.abs(~~(offset / 60)))}:${padZero2(offset % 60)}',
Z: '${offset >= 0 ? \'-\':\'+\'}${padZero2(Math.abs(~~(offset / 60)))}${padZero2(offset % 60)}',
SSS: '${padZero3(now.getMilliseconds())}',
ss: '${padZero2(now.getSeconds())}',
s: '${now.getSeconds()}',
Expand Down
35 changes: 35 additions & 0 deletions benchmark/benchmarkOffset.js
@@ -0,0 +1,35 @@
/* eslint-disable no-console */
'use strict';

var Benchmark = require('benchmark');
var moment = require('moment');
var dateFormat = require('dateformat');
var format = require('date-format');

var DateFormatter = require('../DateFormatter');
var dateFormatter = new DateFormatter();

var DATE_FORMAT = ('ZZ');

const suite = new Benchmark.Suite();

suite
.add('moment', () => {
moment().format(DATE_FORMAT);
})
.add('date-format', () => {
format(DATE_FORMAT, new Date());
})
.add('dateformat', () => {
dateFormat(new Date(), DATE_FORMAT);
})
.add('fast-date-format', () => {
dateFormatter.format(DATE_FORMAT)
})
.on('cycle', function(event) {
console.log(String(event.target));
})
.on('complete', function() {
console.log('Fastest is ' + this.filter('fastest').map('name'));
})
.run({ 'async': true });

0 comments on commit c79b9d3

Please sign in to comment.