Skip to content

Instantly share code, notes, and snippets.

@sh78
Forked from polygonplanet/formatdate.js
Last active May 17, 2018 23:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sh78/6c7618fe81ffec223dbb684f89857f26 to your computer and use it in GitHub Desktop.
Save sh78/6c7618fe81ffec223dbb684f89857f26 to your computer and use it in GitHub Desktop.
/**
* Format a date like YYYY-MM-DD.
*
* @param {string} template
* @param {Date=} [date]
* @return {string}
* @license MIT
*/
function formatDate(template, date) {
// default to today
date = new Date(date || Date.now() - new Date().getTimezoneOffset() * 6e4);
var specs = 'YYYY:MM:DD:HH:mm:ss'.split(':');
return date.toISOString().split(/[-:.TZ]/).reduce(function(template, item, i) {
return template.split(specs[i]).join(item);
}, template);
}
// console.log(formatDate('YYYY-MM-DD')); // ↪ 2015-02-18
// console.log(formatDate('MM/DD/YYYY, HH:mm:ss')); // ↪ 02/18/2015, 19:45:31
// Return a future or past date
function anotherDay(diff, date) {
// default to today
date = new Date(date || Date.now() - new Date().getTimezoneOffset() * 6e4);
// one day in seconds
var oneDay = 24 * 60 * 60 * 1000;
// compute the different day
var theDay = new Date(date.getTime() + (oneDay * diff));
if (date < 0) {
theDay = theDay + oneDay;
}
return theDay;
}
console.log(anotherDay(7)); // date object one week from now
console.log(anotherDay(-2, new Date('2015-02-01T01:23:45.678Z')));
// ↪ Fri Jan 30 2015 17:23:45 GMT-0800 (PST)
function getDateString(options, date, locale) {
// default to today and a nice US format option
options = options || {
weekday: 'long',
year: 'numeric',
month: 'long',
day: 'numeric'
};
date = new Date(date || Date.now() - new Date().getTimezoneOffset() * 6e4);
locale = locale || 'en-US';
return date.toLocaleDateString(locale, options);
}
// var options = {
// weekday: 'long',
// year: 'numeric',
// month: 'long',
// day: 'numeric'
// };
// console.log(getDateString(options, new Date('2012-12-20T01:23:45.678Z'), 'de-DE'));
// → "Mittwoch, 19. Dezember 2012"
// an application may want to use UTC and make that visible
// options.timeZone = 'UTC';
// options.timeZoneName = 'short';
// console.log(getDateString(options, new Date('2012-12-20T01:23:45.678Z')));
// → "Thursday, December 20, 2012, UTC"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment