在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"
這些方法可以根據自己的需求選擇使用,每種方法都有不同的輸出格式。