Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Date Formatting in JavaScript
const months = [
'January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December'
];
const days = [
'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Saturday',
'Sunday'
];
export const formatDate = (date, format) => {
const secondFormats = ['s', 'ss'].sort((a, b) => b.length - a.length);
const minuteFormats = ['m', 'mm'].sort((a, b) => b.length - a.length);
const hourFormats = ['H', 'HH'].sort((a, b) => b.length - a.length);
const dayFormats = ['dd', 'ddd', 'dddd'].sort((a, b) => b.length - a.length);
const monthFormats = ['MM', 'MMM', 'MMMM'].sort((a, b) => b.length - a.length);
const yearFormats = ['yyyy'].sort((a, b) => b.length - a.length);
secondFormats.forEach(sf => {
const regex = new RegExp(sf, 'g');
switch (sf) {
case 'ss':
let seconds = date.getSeconds().toString();
let length = seconds.length;
if (!--length) {
seconds = `0${seconds}`;
}
format = format.replace(regex, seconds);
break;
case 's':
format = format.replace(regex, date.getSeconds().toString());
break;
default:
return;
}
});
minuteFormats.forEach(mf => {
const regex = new RegExp(mf, 'g');
switch (mf) {
case 'mm':
let minutes = date.getMinutes().toString();
let length = minutes.length;
if (!--length) {
minutes = `0${minutes}`;
}
format = format.replace(regex, minutes);
break;
case 'm':
format = format.replace(regex, date.getMinutes().toString());
break;
default:
return;
}
});
hourFormats.forEach(hf => {
const regex = new RegExp(hf, 'g');
switch (hf) {
case 'HH':
let hours = date.getHours().toString();
let length = hours.length;
if (!--length) {
hours = `0${hours}`;
}
format = format.replace(regex, hours);
break;
case 'H':
format = format.replace(regex, date.getHours().toString());
break;
default:
return;
}
});
dayFormats.forEach(df => {
const regex = new RegExp(df, 'g');
switch (df) {
case 'dddd':
format = format.replace(regex, days[date.getDay()]);
break;
case 'ddd':
format = format.replace(regex, days[date.getDay()].substr(0, df.length));
break;
case 'dd':
format = format.replace(regex, date.getDate().toString());
break;
default:
return;
}
});
monthFormats.forEach(mf => {
const regex = new RegExp(mf, 'g');
switch (mf) {
case 'MMMM':
format = format.replace(regex, months[date.getMonth()]);
break;
case 'MMM':
format = format.replace(regex, months[date.getMonth()].substr(0, mf.length));
break;
case 'MM':
let month = date.getMonth();
format = format.replace(regex, (++month).toString());
break;
default:
return;
}
});
yearFormats.forEach(yf => {
const regex = new RegExp(yf, 'g');
switch (yf) {
case 'yyyy':
format = format.replace(regex, date.getFullYear().toString());
break;
default:
return;
}
});
return format;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.