Вы можете вырезать компоненты даты и затем упорядочить их в нужном вам порядке.
Необходимо настроить часы и меридиан.
const DateComponenents = (() => {
const fields = ['YYYY', 'MM', 'DD', 'HH', 'mm', 'ss', 'SSS'];
const pattern = /^(\d{4})\-(\d{2})\-(\d{2})T(\d{2}):(\d{2}):(\d{2})\.(\d{3})Z$/;
return (date) => {
return date.toISOString().match(pattern).slice(1).reduce((r, v, i) => {
return Object.assign(r, { [fields[i]]: v });
}, {});
}
})();
function formatDate(date) {
let c = DateComponenents(date); // Extract the componenents
let hours = parseInt(c['HH'], 10); // Grab the 24-hour piece
let meridiem = hours < 12 ? 'AM' : 'PM'; // Determine AM or PM
hours %= 12; // Modular 0 - 12
if (hours === 0) hours = 12; // Shift 0am to 12am
hours = ('00' + hours).substr(-2); // Pad the hours
return `${c['YYYY']}-${c['MM']}-${c['DD']} T ${hours}:${c['mm']} ${meridiem}`
}
console.log(formatDate(new Date()));
.as-console-wrapper { top: 0; max-height: 100% !important; }
Вот более динамичная версия, которая поддерживает пользовательское форматирование ...
const DateComponenents = (() => {
const fields = ['YYYY', 'MM', 'DD', 'HH', 'mm', 'ss', 'SSS'];
const pattern = /^(\d{4})\-(\d{2})\-(\d{2})T(\d{2}):(\d{2}):(\d{2})\.(\d{3})Z$/;
const applyRest = (c) => {
let hours = parseInt(c['HH'], 10);
let meridiem = hours < 12 ? 'AM' : 'PM';
hours %= 12; hours = ('00' + (hours === 0 ? 12 : hours)).substr(-2);
return Object.assign(c, { 'hh' : hours, 'A' : meridiem });
}
return (date) => {
return applyRest(date.toISOString().match(pattern).slice(1).reduce((r, v, i) => {
return Object.assign(r, { [fields[i]]: v });
}, {}));
};
})();
function formatDate(date, format) {
return (c => format.replace(/\w+/g, key => c[key] || key))(DateComponenents(date));
}
console.log(formatDate(new Date(), 'YYYY-MM-DD T hh:mm A'));
.as-console-wrapper { top: 0; max-height: 100% !important; }