Initiallly, It's a best practice to get dates from server in ISO-8601 format YYYY-MM-DDTHH:mm:ss.sssZ
. That helps us handle dates in a better way.
Nowadays, the native Intl API has a good browser support and we can use it easily to achieve that:
const dateInIsoFormatFromServer = "2022-06-03T19:38:34.203Z";
const date = new Date(dateInIsoFormatFromServer);
const formatter1 = new Intl.DateTimeFormat("en-US");
console.log("Format for United States locale: ", formatter1.format(date));
// Format for United States locale: 6/3/2022
const formatter2 = new Intl.DateTimeFormat("pt-BR");
console.log("Format for Brasil locale: ", formatter2.format(date));
// Format for Brasil locale: 03/06/2022
const formatter3 = new Intl.DateTimeFormat("es-AR");
console.log("Format for Argentina locale: ", formatter3.format(date));
// Format for Argentina locale: 3/6/2022
Locale string here could be sent from server to set in Intl.DateTimeFormat
method. However, you could get the locale from user browser with navigator object and dinamically set that locale to formatter:
const dateInIsoFormatFromServer = "2022-06-03T19:38:34.203Z";
const date = new Date(dateInIsoFormatFromServer);
const browserLocale =
window.navigator.language || window.navigator.browserLanguage;
const formatter1 = new Intl.DateTimeFormat(browserLocale);
console.log("Format for browser locale: ", formatter1.format(date));
// Format for browser locale: 03/06/2022
// * My browserLocale is pt-BR
if necessary, you can set options to customize the format output:
const dateInIsoFormatFromServer = "2022-06-03T19:38:34.203Z";
const date = new Date(dateInIsoFormatFromServer);
const browserLocale =
window.navigator.language || window.navigator.browserLanguage;
const options = {
year: "numeric",
month: "numeric",
day: "numeric",
hour: "numeric",
minute: "numeric",
second: "numeric",
hour12: false
};
const formatter1 = new Intl.DateTimeFormat(browserLocale, options);
console.log("Format for browser locale with options: ", formatter1.format(date));
// Format for browser locale with options: 03/06/2022 12:38:34
// * My browserLocale is pt-BR