Skip to content

Instantly share code, notes, and snippets.

@stracker-phil
Created June 20, 2019 09:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save stracker-phil/c7b68ea0b1d5bbb97af0a6a3dc66e0d9 to your computer and use it in GitHub Desktop.
Save stracker-phil/c7b68ea0b1d5bbb97af0a6a3dc66e0d9 to your computer and use it in GitHub Desktop.
A short ES6 function that converts a JS Date object into a localized date-string. It takes the same parameters as the PHP `date` function.
// Detects the browser locale for Date translations.
const locale = (navigator.languages && navigator.languages.length) ?
navigator.languages[0] :
navigator.language ?
navigator.language :
'en';
// Date formatter with php-compatible format syntax
export const formatDate = (format, date) => {
if (format === undefined) {
format = 'Y-m-d'
}
if (date === undefined) {
// No date specified means "now"
date = new Date()
} else if (!isNaN(date) && typeof date !== 'object') {
// Treat integers as PHP timestamps.
date = new Date(date * 1000)
} else if (typeof date === 'string') {
// Strings are date strings, e.g. '2019-06-01'
date = new Date(date)
}
const hour24 = date.getHours()
const hour12 = (date.getHours() % 12) || 12
// Define all known date placeholders.
const parts = {
Y: date.getFullYear().toString(),
y: ('00' + (date.getYear() - 100)).toString().slice(-2),
m: ('0' + (date.getMonth() + 1)).toString().slice(-2),
n: (date.getMonth() + 1).toString(),
d: ('0' + date.getDate()).toString().slice(-2),
j: date.getDate().toString(),
H: ('0' + hour24).toString().slice(-2),
h: ('0' + hour12).toString().slice(-2),
G: hour24.toString(),
g: hour12.toString(),
a: hour24 >= 12 && hour24 < 24 ? 'pm' : 'am',
A: hour24 >= 12 && hour24 < 24 ? 'PM' : 'AM',
i: ('0' + date.getMinutes()).toString().slice(-2),
s: ('0' + date.getSeconds()).toString().slice(-2),
S: ['st','nd','rd',,,,,,,,,,,,,,,,,,'st','nd','rd',,,,,,,,'st'][date.getDate()-1] || 'th',
w: date.getDay(),
N: date.getDay() > 0 ? date.getDay() : 7,
D: date.toLocaleString(locale, { weekday: "short" }),
l: date.toLocaleString(locale, { weekday: "long" }),
M: date.toLocaleString(locale, { month: "short" }),
F: date.toLocaleString(locale, { month: "long" })
}
const modifiers = Object.keys(parts).join('')
const reDate = new RegExp('[' + modifiers + ']', 'g')
return format.replace(reDate, $0 => parts[$0])
}
/*
Examples:
console.log( formatDate() ); // 2019-06-20
console.log( formatDate('H:i:s') ); // 10:22:32
console.log( formatDate('F, j. M Y') ); // Donnerstag, 20. Juni 2019 (with German locale)
console.log( formatDate('F, jS M Y') ); // Thursday, 20th June 2019 (with English locale)
var dates = [
new Date('2019-03-01'),
new Date('2019-03-02'),
new Date('2019-03-03'),
new Date('2019-03-04'),
]
dates.forEach(date => {
console.log( formatDate('jS M Y', date) )
})
var times = [
new Date('2019-01-01 00:00'),
new Date('2019-01-01 00:01'),
new Date('2019-01-01 24:00'),
new Date('2019-01-01 11:59'),
new Date('2019-01-01 12:00'),
new Date('2019-01-01 12:01'),
new Date('2019-01-01 13:00'),
]
times.forEach(time => {
console.log( formatDate('G:iA', time), '/', formatDate('H:i', time) )
})
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment