Skip to content

Instantly share code, notes, and snippets.

@artfulrobot
Last active November 15, 2019 11:33
Show Gist options
  • Save artfulrobot/b34143714e6dbb4897b9aa83230a26e7 to your computer and use it in GitHub Desktop.
Save artfulrobot/b34143714e6dbb4897b9aa83230a26e7 to your computer and use it in GitHub Desktop.
Limited English only Jacascript version of php's date formatter
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title></title>
</head>
<body>
<script src="Date-arFormat.js" ></script>
<ul>
<script>
var tests = [
['2019-02-01 01:02:03', 'Y-m-d H:i:s', '2019-02-01 01:02:03' ],
['2019-02-01 01:02:03', 'j M Y a', '1 Feb 2019 am' ],
['2019-02-28 13:12:14', 'j M g:i:s a', '28 Feb 1:12:14 pm' ],
['2019-02-01 01:02:03', 'F', 'February' ],
];
tests.forEach(a => {
const d = new Date(a[0]);
var f = d.arFormat(a[1]);
if (f === a[2]) {
document.write('<li>✔ ' + a[1] + '</li>');
}
else {
document.write('<li>✖ Failed:<br/><pre>' + JSON.stringify(a) + "\nGot: " + JSON.stringify(f) + "\nDate: " + d.toLocaleString() + '</pre></li>');
}
});
// Test cache.
var d = new Date('2019-11-15 00:00:00');
var f = d.arFormat('Y');
if (f !== '2019') {
// Should not happen as tested above already.
document.write('<li>✖ failed to get year</li>');
}
else {
// inject a daft value into the cache.
d.artfulrobot.cache.Y = 'foo';
f = d.arFormat('Y');
if (f !== 'foo') {
document.write('<li>✖ subsequent call did not use cache!</li>');
}
else {
// OK, cache worked, but what if we update the date.
d.setFullYear('2016');
f = d.arFormat('Y');
if (f !== '2016') {
document.write('<li>✖ failed to reset cache when date changed.</li>');
}
else {
document.write('<li>✔ Cache seems to be working.</li>');
}
}
}
</script>
</ul>
</body>
</html>
/**
* Simple and limited English implementation of PHP's date()
*
* Usage:
*
* const d = new Date();
* const format = 'j M Y H:i:s';
* const s = d.arFormat(format);
*
* Results are cached
*
* Versions:
* - 1.0 Released 2019-11-15
*/
Date.prototype.arFormat = function(format) {
if (!this.artfulrobot || this.artfulrobot.cacheValidWhenDateWas !== this.toString()) {
// (re) initialise empty cache.
this.artfulrobot = { cache: {}, cacheValidWhenDateWas: this.toString() };
}
if (!(format in this.artfulrobot.cache)) {
if (! this.artfulrobot.formats) {
// Initialise lookup table.
var zeroPad = v => { s = v.toString(); while (s.length < 2) s = '0' + s; return s; };
const hours = this.getHours();
this.artfulrobot.formats = {
Y: this.getFullYear().toString(),
m: zeroPad(this.getMonth()+1),
d: zeroPad(this.getDate()),
H: zeroPad(hours),
g: ((hours > 12) ? (hours - 12) : hours).toString(),
i: zeroPad(this.getMinutes()),
s: zeroPad(this.getSeconds()),
j: this.getDate().toString(),
F: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'][this.getMonth()],
M: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'][this.getMonth()],
a: (hours < 12) ? 'am' : 'pm',
A: (hours < 12) ? 'AM' : 'PM',
};
}
const formats = this.artfulrobot.formats;
// Calculate format value and save to cache.
this.artfulrobot.cache[format] = format.replace(/[dmYHgisjFMaA]/g, m => formats[m]);
}
// Return from cache.
return this.artfulrobot.cache[format];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment