创建一个TypeScrip(TS)函数,以字符串形式返回格式化的日期:
function formatDate(inputDate) {
// Convert the input string to a Date object
const date = new Date(inputDate);
// Get the day with leading zeros
const day = String(date.getDate()).padStart(2, '0');
// Get the month with leading zeros
const month = String(date.getMonth() + 1).padStart(2, '0');
// Get the year
const year = date.getFullYear();
// Get the hours with leading zeros
const hours = String(date.getHours()).padStart(2, '0');
// Get the minutes with leading zeros
const minutes = String(date.getMinutes()).padStart(2, '0');
// Format the date as dd/MM/yyyy HH:mm
const formattedDate = `${day}/${month}/${year} ${hours}:${minutes}`;
return formattedDate;
}
现在使用上面的函数获得格式化的日期,如下所示:
const inputDate = '2023-09-18T12:52:45.000Z';
const formattedDate = formatDate(inputDate);
console.log(formattedDate); // Output: "18/09/2023 18:22"
function formatDate(inputDate) {
// Convert the input string to a Date object
const date = new Date(inputDate);
// Get the day with leading zeros
const day = String(date.getDate()).padStart(2, '0');
// Get the month with leading zeros (Note: Months are zero-based)
const month = String(date.getMonth() + 1).padStart(2, '0');
// Get the year
const year = date.getFullYear();
// Get the hours with leading zeros
const hours = String(date.getHours()).padStart(2, '0');
// Get the minutes with leading zeros
const minutes = String(date.getMinutes()).padStart(2, '0');
// Format the date as dd/MM/yyyy HH:mm
const formattedDate = `${day}/${month}/${year} ${hours}:${minutes}`;
return formattedDate;
}
const inputDate = '2023-09-18T12:52:45.000Z'; // Replace this with desired date
const formattedDate = formatDate(inputDate);
console.log(formattedDate);