Skip to content

Instantly share code, notes, and snippets.

@bitsmanent
Last active December 3, 2018 13:29
Show Gist options
  • Select an option

  • Save bitsmanent/5e8b350ab390887246df2b6bc8aca906 to your computer and use it in GitHub Desktop.

Select an option

Save bitsmanent/5e8b350ab390887246df2b6bc8aca906 to your computer and use it in GitHub Desktop.
JavaScript strftime() implementation
function pad(s, len, c, pr) {
var rest;
/* prevent arithmetic issues */
s = s.toString();
c = c.toString();
rest = len - s.length;
if(rest <= 0)
return s;
[...Array(rest)].forEach(() => s=pr ? s+c : c+s);
return s;
}
/* An attempt to have a consistent strftime().
* Not everything is implemented, only what makes sense.
* Reference: http://php.net/manual/en/function.strftime.php */
function strftime(fmt, d) {
var ret = "", i, len, c;
var txt = (d, o) => {
d = d.toLocaleString(navigator.language, o).toString();
/* not always capitalized (see it-IT) */
d = d[0].toUpperCase() + d.substring(1);
return d;
};
for(i = 0, len = fmt.length; i < len; ++i) {
c = fmt[i];
if(c != '%' || fmt[++i] == '%') {
ret += c;
continue;
}
c = fmt[i];
switch(c) {
case 'a': ret += txt(d, {weekday:"short"}); break;
case 'A': ret += txt(d, {weekday:"long"}); break;
case 'b': ret += txt(d, {month:"short"}); break;
case 'B': ret += txt(d, {month:"long"}); break;
case 'd': ret += pad(d.getDate(), 2, 0); break;
case 'e': ret += pad(d.getDate(), 2, ' '); break;
case 'm': ret += pad(d.getMonth()+1, 2, 0); break;
case 'H': ret += pad(d.getHours(), 2, 0); break;
case 'M': ret += pad(d.getMinutes(), 2, 0); break;
case 'S': ret += pad(d.getSeconds(), 2, 0); break;
case 'Y': ret += d.getFullYear(); break;
case 'y':
/* recycle c */
c = d.getFullYear().toString();
ret += c.substring(c.length - 2);
break;
default: console.warn(c+": invalid format operator"); break;
}
}
return ret;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment