Last active
March 10, 2016 08:07
-
-
Save jcayzac/c5085c14831829d04d61 to your computer and use it in GitHub Desktop.
strftime.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ES6 strftime(3) function that supports FDxcAaBbCdemuwYynt% for en_US only | |
// (only for dates, not datetimes) | |
Date.prototype.format = function(f) { | |
const t=this,p=(v,f)=>v.toString().length==1?f+v:v,Y=t.getFullYear(),mo=t.getMonth()+1,dm=t.getDate(),u=t.getDay(),A=['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'][u%7],B=['January','February','March','April','May','June','July','August','September','October','November','December'][mo-1] | |
return ['%Y-%m-%d','%m/%d/%y','%m/%d/%Y','%a %b %e %Y',A,A.slice(0,3),B,B.slice(0,3),Y/100|0,p(dm,'0'),p(dm,' '),p(mo,'0'),u,u%7,Y,Y%100,'\n','\t','%'].reduce((_, s, i)=>_.replace(new RegExp('%'+'FDxcAaBbCdemuwYynt%'[i],'g'),s),f) | |
} | |
// Unit tests | |
!() => { | |
var date = new Date('2016-04-02'), assert = require('assert') | |
assert.equal(date.format('%F _ %Y _ %D _ %x'), '2016-04-02 _ 2016 _ 04/02/16 _ 04/02/2016') | |
assert.equal(date.format('%A _ %a _ %B _ %b'), 'Saturday _ Sat _ April _ Apr') | |
assert.equal(date.format('%C _ %c _ %\d _ %e'), '20 _ Sat Apr 2 2016 _ 02 _ 2') | |
assert.equal(date.format('%m _ %u _ %w _ %Y'), '04 _ 6 _ 6 _ 2016') | |
assert.equal(date.format('%y _ %n _ %t _ %%'), '16 _ \n _ \t _ %') | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment