Skip to content

Instantly share code, notes, and snippets.

@darklight721
Last active December 20, 2015 10:59
Show Gist options
  • Save darklight721/6119407 to your computer and use it in GitHub Desktop.
Save darklight721/6119407 to your computer and use it in GitHub Desktop.
d8s.js - A simple js date formatter
/*
* d8s.js - a simple js date formatter
* Usage:
* d8s().print('MM-DD-YY hh:mm:ss'); // outputs: 07-21-13 10:25:01
* d8s('2013/7/21' ,'YYYY/M/D').print('DDD of MMMM, YYYY'); // outputs: 21st of July, 2013
* d8s('Sep. 5, 2013 13:30', 'MMM. D, YYYY HH:mm').date(); // returns the Date object with the set date
* d8s(new Date(1995,11,17)).print('DD.MM.YYYY'); // outputs: 17.11.1995
*/
window.d8s = window.d8s || (function(){
// formats definition
var ordinals = ['th', 'st', 'nd', 'rd'],
months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
mons = months.map(function(m){ return m.substr(0, 3); }),
century = Math.floor((new Date()).getFullYear() / 100),
rgxD12 = '(\\d\\d?)',
rgxD2 = '(\\d\\d)',
formats = {
// day
'D' : {
get: function(date) { return date.getDate(); },
set: function(date, day) { date.setDate(day); },
rgx: rgxD12
},
'DD' : {
get: function(date) { return to2Digits(formats.D.get(date)); },
set: function(date, day) { formats.D.set(date, day); },
rgx: rgxD2
},
'DDD' : {
get: function(date) {
var day = formats.D.get(date);
return day + ((day < 11 || day > 13) && ordinals[day % 10] || ordinals[0]);
},
set: function(date, day) { formats.D.set(date, day); },
rgx: rgxD12 + '(?:'+ ordinals.join('|') +')'
},
// month
'M' : {
get: function(date) { return date.getMonth() + 1; },
set: function(date, month) { date.setMonth(month - 1); },
rgx: rgxD12
},
'MM' : {
get: function(date) { return to2Digits(formats.M.get(date)); },
set: function(date, month) { formats.M.set(date, month); },
rgx: rgxD2
},
'MMM' : {
get: function(date) { return mons[formats.M.get(date) - 1]; },
set: function(date, month) { formats.M.set(date, mons.indexOf(month) + 1); },
rgx: '('+ mons.join('|') +')'
},
'MMMM': {
get: function(date) { return months[formats.M.get(date) - 1]; },
set: function(date, month) { formats.M.set(date, months.indexOf(month) + 1); },
rgx: '('+ months.join('|') +')'
},
// year
'YY' : {
get: function(date) { return to2Digits(formats.YYYY.get(date) % 100); },
set: function(date, year) { formats.YYYY.set(date, century + year); },
rgx: rgxD2
},
'YYYY': {
get: function(date) { return date.getFullYear(); },
set: function(date, year) { date.setFullYear(year); },
rgx: '(\\d{4})'
},
// hour
'h' : {
get: function(date) { return formats.H.get(date) % 12; },
set: function(date, hour) { formats.H.set(date, hour); },
rgx: rgxD12
},
'hh' : {
get: function(date) { return to2Digits(formats.h.get(date)); },
set: function(date, hour) { formats.H.set(date, hour); },
rgx: rgxD2
},
'H' : {
get: function(date) { return date.getHours(); },
set: function(date, hour) { date.setHours(hour); },
rgx: rgxD12
},
'HH' : {
get: function(date) { return to2Digits(formats.H.get(date)); },
set: function(date, hour) { formats.H.set(date, hour); },
rgx: rgxD2
},
// minute
'm' : {
get: function(date) { return date.getMinutes(); },
set: function(date, min) { date.setMinutes(min); },
rgx: rgxD12
},
'mm' : {
get: function(date) { return to2Digits(formats.m.get(date)); },
set: function(date, min) { formats.m.set(date, min); },
rgx: rgxD2
},
// second
's' : {
get: function(date) { return date.getSeconds(); },
set: function(date, sec) { date.setSeconds(sec); },
rgx: rgxD12
},
'ss' : {
get: function(date) { return to2Digits(formats.s.get(date)); },
set: function(date, sec) { formats.s.set(date, sec); },
rgx: rgxD2
},
// meridian
'p' : {
get: function(date) { return formats.H.get(date) < 12 ? 'am' : 'pm' },
set: function(date, pm) {
if (pm === 'pm') {
var hour = formats.H.get(date);
if (hour < 12)
formats.H.set(date, hour + 12);
}
},
rgx: '(am|pm)'
},
'P' : {
get: function(date) { return formats.p.get(date).toUpperCase(); },
set: function(date, pm) { formats.p.set(date, pm.toLowerCase()); },
rgx: '(AM|PM)'
},
// dividers
'/' : {
rgx: '\\/'
},
'.' : {
rgx: '\\.'
}
};
// internal functions
function tokenize(string) {
var tokens = [], token = '';
for (var i = 0, l = string.length; i < l; ++i) {
var newToken = string[i];
if (token[0] === newToken) {
token += newToken;
}
else {
tokens.push(token);
token = newToken;
}
}
tokens.push(token);
return tokens;
}
function to2Digits(num) {
return num < 10 ? '0' + num : num;
}
function isString(data) {
return typeof data === 'string';
}
// api obj
function d8s(date, format) {
this._date = new Date();
this._scanRegExp = null;
this._scanTokens = [];
this._printTokens = [];
this.scan(date, format);
}
d8s.prototype.scan = function(date, format) {
if (isString(date)) {
this.setScanFormat(format);
var dateObj = this._date,
matches = date.match(this._scanRegExp),
index = 1;
matches && this._scanTokens.forEach(function(token) {
var format = formats[token];
format && format.set && format.set(dateObj, matches[index++]);
});
}
else {
this._date.setTime(date instanceof Date ? date.getTime() : Date.now());
}
return this;
};
d8s.prototype.print = function(format) {
this.setPrintFormat(format);
var dateObj = this._date;
return this._printTokens.reduce(function(formattedDate, token){
var format = formats[token];
return formattedDate + (format && format.get ? format.get(dateObj) : token);
}, '');
};
d8s.prototype.date = function() {
return new Date(this._date.getTime());
};
d8s.prototype.setScanFormat = function(format) {
if (format && isString(format)) {
this._scanTokens = tokenize(format);
this._scanRegExp = new RegExp(this._scanTokens.reduce(function(regexp, token) {
var format = formats[token];
return regexp + (format && format.rgx ? format.rgx : token);
}, '^'));
}
return this;
}
d8s.prototype.setPrintFormat = function(format) {
if (format && isString(format)) {
this._printTokens = tokenize(format);
}
return this;
};
// constructor function
return function(date, format) {
return new d8s(date, format);
};
})();
window.d8s=window.d8s||function(){function l(a,c){var f=k(c),m=f.reduce(function(a,c){var f=b[c];return a+(f&&f.rgx?f.rgx:c)},"^"),d=a.match(RegExp(m)),e=1;d&&f.forEach(function(a){(a=b[a])&&a.set&&a.set(d[e++])})}function k(a){for(var b=[],c="",d=0;d<a.length;++d){var e=a[d];c[0]===e?c+=e:(b.push(c),c=e)}b.push(c);return b}function d(a){return 10>a?"0"+a:a}var c=new Date,g=["th","st","nd","rd"],e="January February March April May June July August September October November December".split(" "),h=
e.map(function(a){return a.substr(0,3)}),b={D:{get:function(){return c.getDate()},set:function(a){c.setDate(a)},rgx:"(\\d{1,2})"},DD:{get:function(){return d(b.D.get())},set:function(a){b.D.set(a)},rgx:"(\\d{2})"},DDD:{get:function(){var a=b.D.get();return a+(g[a%10]||g[0])},set:function(a){b.D.set(a)},rgx:"(\\d{1,2})(?:"+g.join("|")+")"},M:{get:function(){return c.getMonth()+1},set:function(a){c.setMonth(a-1)},rgx:"(\\d{1,2})"},MM:{get:function(){return d(b.M.get())},set:function(a){b.M.set(a)},
rgx:"(\\d{2})"},MMM:{get:function(){return h[b.M.get()-1]},set:function(a){b.M.set(h.indexOf(a)+1)},rgx:"("+h.join("|")+")"},MMMM:{get:function(){return e[b.M.get()-1]},set:function(a){b.M.set(e.indexOf(a)+1)},rgx:"("+e.join("|")+")"},YY:{get:function(){return d(b.YYYY.get()%100)},set:function(a){b.YYYY.set("20"+a)},rgx:"(\\d{2})"},YYYY:{get:function(){return c.getFullYear()},set:function(a){c.setFullYear(a)},rgx:"(\\d{4})"},h:{get:function(){return b.H.get()%12},set:function(a){b.H.set(a)},rgx:"(\\d{1,2})"},
hh:{get:function(){return d(b.h.get())},set:function(a){b.H.set(a)},rgx:"(\\d{2})"},H:{get:function(){return c.getHours()},set:function(a){c.setHours(a)},rgx:"(\\d{1,2})"},HH:{get:function(){return d(b.H.get())},set:function(a){b.H.set(a)},rgx:"(\\d{2})"},m:{get:function(){return c.getMinutes()},set:function(a){c.setMinutes(a)},rgx:"(\\d{1,2})"},mm:{get:function(){return d(b.m.get())},set:function(a){b.m.set(a)},rgx:"(\\d{2})"},s:{get:function(){return c.getSeconds()},set:function(a){c.setSeconds(a)},
rgx:"(\\d{1,2})"},ss:{get:function(){return d(b.s.get())},set:function(a){b.s.set(a)},rgx:"(\\d{2})"},"/":{rgx:"\\/"},".":{rgx:"\\."}},n={print:function(a){return k(a).reduce(function(a,c){var d=b[c];return a+(d&&d.get?d.get():c)},"")},date:function(){return new Date(c.getTime())}};return function(a,b){"string"===typeof a&&"string"===typeof b?l(a,b):a instanceof Date?c.setTime(a.getTime()):c.setTime(Date.now());return n}}();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment