Skip to content

Instantly share code, notes, and snippets.

@anbinh
Forked from atesgoral/LICENSE.txt
Last active December 15, 2015 14:29
Show Gist options
  • Save anbinh/5275177 to your computer and use it in GitHub Desktop.
Save anbinh/5275177 to your computer and use it in GitHub Desktop.

Instead of using classical format specifiers like "YYYY", "MM", "HH", "mm" etc., this function uses the Date instance getters like getFullYear, getMonth, etc., with support for zero-padding.

For example, instead of:

"YYYY-MM-DD HH:mm:ss"

you can use:

"{FullYear}-{Month:2}-{Date:2} {Hours:2}:{Minutes:2}:{Seconds:2}"

Verbose, but more human-friendly. And can be done within 140 bytes!

function (
d, // Date instance
f // Format string
) {
return f.replace( // Replace all tokens
/{(.+?)(?::(.*?))?}/g, // {<part>:<padding>}
function (
v, // Matched string (ignored, used as local var)
c, // Date component name
p // Padding amount
) {
for(v = d["get" + c]() // Execute date component getter
+ /h/.test(c) // Increment Mont(h) components by 1
+ ""; // Cast to String
v.length < p; // While padding needed,
v = 0 + v); // pad with zeros
return v // Return padded result
})
}
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
Version 2, December 2004
Copyright (C) 2011 Ates Goral <http://magnetiq.com>
Everyone is permitted to copy and distribute verbatim or modified
copies of this license document, and changing it is allowed as long
as the name is changed.
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. You just DO WHAT THE FUCK YOU WANT TO.
function(d,f){return f.replace(/{(.+?)(?::(.*?))?}/g,function(v,c,p){for(v=d["get"+c]()+/h/.test(c)+"";v.length<p;v=0+v);return v})}
{
"name": "formatDate",
"description": "Date formatter",
"keywords": [
"date",
"string",
"formatting",
"conversion"
]
}
<!DOCTYPE html>
<title>Foo</title>
<div>Expected value: <b>2011-06-03 02:33:54</b></div>
<div>Actual value: <b id="ret"></b></div>
<script>
var formatDate = function(d,f){return f.replace(/{(.+?)(?::(.*?))?}/g,function(v,c,p){for(v=d["get"+c]()+/h/.test(c)+"";v.length<p;v=0+v);return v})};
document.getElementById( "ret" ).innerHTML = formatDate(
new Date(2011, 5, 3, 2, 33, 54, 0),
"{FullYear}-{Month:2}-{Date:2} {Hours:2}:{Minutes:2}:{Seconds:2}"
);
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment