在JavaScript中,有几种格式化时间的方法,以下是一些常用的方法:
toLocaleString()
方法:const date = new Date();
const formattedDate = date.toLocaleString();
console.log(formattedDate); // Output: "5/3/2022, 9:45:30 PM" (based on the user's locale)
toISOString()
方法:const date = new Date();
const formattedDate = date.toISOString();
console.log(formattedDate); // Output: "2022-05-03T21:45:30.000Z"
const date = new Date();
const formattedDate = moment(date).format('YYYY-MM-DD HH:mm:ss');
console.log(formattedDate); // Output: "2022-05-03 21:45:30"
const date = new Date();
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0');
const day = String(date.getDate()).padStart(2, '0');
const hours = String(date.getHours()).padStart(2, '0');
const minutes = String(date.getMinutes()).padStart(2, '0');
const seconds = String(date.getSeconds()).padStart(2, '0');
const formattedDate = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
console.log(formattedDate); // Output: "2022-05-03 21:45:30"
这些方法可以根据自己的需求选择使用,每种方法都有不同的输出格式。