Skip to content

Instantly share code, notes, and snippets.

@liamnewmarch
Created November 10, 2016 16:24
Show Gist options
  • Save liamnewmarch/823f97c99bc575f46126d7cb5ba5dbc9 to your computer and use it in GitHub Desktop.
Save liamnewmarch/823f97c99bc575f46126d7cb5ba5dbc9 to your computer and use it in GitHub Desktop.
A simple class for formatting dates.
class DateFormat {
constructor(format) {
this.format = format instanceof String ? format : String(format);
}
get _formatMap() {
return ['yyyy', 'yy', 'mm', 'm', 'dd', 'd', 'hh', 'h', 'ii', 'i', 'ss', 's'];
}
format(date) {
this.date = date instanceof Date ? date : new Date(date);
let output = '';
while (format.length) {
const key = this._formatMap.find(key => {
return format.startsWith(key);
});
if (key) {
output += this[`_${key}`](this.date);
format = format.substr(key.length);
} else {
output += format[0];
format = format.substr(1);
}
}
return output;
}
_yyyy(date) {
const year = date.getFullYear();
return String(year).padStart(4, 0);
}
_yy(date) {
const year = date.getYear();
return String(year).padStart(2, 0);
}
_mm(date) {
const month = date.getMonth() + 1;
return String(month).padStart(2, 0)
}
_m(date) {
const month = date.getMonth() + 1;
return String(month);
}
_dd(date) {
const day = date.getDate();
return String(day).padStart(2, 0);
}
_d(date) {
const day = date.getDate();
return String(day);
}
_hh(date) {
const hours = date.getHours();
return String(hours).padStart(2, 0);
}
_h(date) {
const hours = date.getHours();
return String(hours);
}
_ii(date) {
const minutes = date.getMinutes();
return String(minutes).padStart(2, 0);
}
_i(date) {
const minutes = date.getMinutes();
return String(minutes);
}
_ss(date) {
const seconds = date.getSeconds();
return String(seconds).padStart(2, 0);
}
_s(date) {
const seconds = date.getSeconds();
return String(seconds);
}
}
Date.prototype.format = function(format) {
return new DateFormat(format).format(date);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment