Format Dates
Sat Sep 24 2022 07:00:56 GMT+0000 (Coordinated Universal Time)
Saved by
@Kristi
#javascript
/**
*
* @param {Date} dateObject
*/
//Formatting Dates
function formateDate(dateObject) {
const parts = {
date: dateObject.getDate(),
month: dateObject.getMonth() + 1,
year: dateObject.getFullYear(),
hour: dateObject.getHours() % 12 || 12,
minute: dateObject.getMinutes().toString().padStart(2, '0'),
amOrPm: dateObject.getHours() < 12 ? 'AM' : 'PM',
};
return `${parts.date}/${parts.month}/${parts.year} ${parts.hour}:${parts.minute} ${parts.amOrPm}`;
}
const myDate = new Date();
const myDateFormatted = formateDate(myDate);
console.log(myDateFormatted);
//INTERNATINALIZING DATES new Intl.DateTimeFormat().format(date)
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat
const currentDate = new Date();
labelDate.textContent = new Intl.DateTimeFormat('de-DE').format(currentDate);
//Using options
let options = { weekday: 'long' //'short' 'narrow',
year: 'numeric',
month: 'long' //'2-digit',
day: 'numeric',
hour: 'numeric',
minute: 'numeric',
second: 'numeric',
hour12: false,
};
//Instead of manually setting the language 'de-DE' you can also detect the user's browser preferred language
const localLanguage = navigator.language;
console.log(new Intl.DateTimeFormat(localLanguage, options).format(currentDate));
// → "Donnerstag, 20. Dezember 2012 - 17:29:01"
content_copyCOPY
https://www.youtube.com/watch?v=50cDIUKlQ8g
Comments