Skip to content

Instantly share code, notes, and snippets.

@jherax
Last active May 30, 2020 15:38
Show Gist options
  • Save jherax/e58ee9f560764a72a90ded5fc53e4105 to your computer and use it in GitHub Desktop.
Save jherax/e58ee9f560764a72a90ded5fc53e4105 to your computer and use it in GitHub Desktop.
Changes the format of a string-date
/**
* Changes the format of a string-date.
*
* @param {Object | String} options: it can be a String with the date, or an Object with the following properties:
* - {String} date: the entry date to change the format
* - {String} inputFormat: the format of the entry date
* - {String} outputFormat: the format of the output date
* @return {String}
*/
const formatDate = (() => {
const _YMD = (/[yMd]+/gi);
const _Y = (/y+/);
const _M = (/M+/);
const _D = (/d+/);
const defaults = {
date: null,
inputFormat: 'yyyy/MM/dd',
outputFormat: 'MM/dd/yyyy',
};
return (options) => {
let d, m, y; // eslint-disable-line
if (typeof options === 'string') {
options = { date: options };
}
const opt = Object.assign({}, defaults, options);
const dateParts = opt.date.split(/\D/);
const formatParts = opt.inputFormat.split(/\W/);
for (let i = 0; i < formatParts.length; i += 1) {
if (_Y.test(formatParts[i])) { y = dateParts[i]; continue; }
if (_M.test(formatParts[i])) { m = dateParts[i]; continue; }
if (_D.test(formatParts[i])) { d = dateParts[i]; continue; }
}
return opt.outputFormat.replace(_YMD, (match) => { // eslint-disable-line
if (_Y.test(match)) return y;
if (_M.test(match)) return m;
if (_D.test(match)) return d;
});
};
})();
var date = '2016/06/30';
// default inputFormat: 'yyyy/MM/dd'
// default outputFormat: 'MM/dd/yyyy'
var output = formatDate(date);
console.log(date, '->', output);
// expected:
// 2016/06/30 -> 06/30/2016
//-----------------------------------
date = '1995-12-17T03:24:59-05:00';
output = formatDate({
date,
inputFormat: 'yyyy-MM-dd',
outputFormat: 'dd/MM/yyyy'
});
console.log(date, '->', output);
// expected:
// 1995-12-17T03:24:59-05:00 -> 17/12/1995
@dbdario025
Copy link

Great!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment