溫馨提示×

js格式化時間的方法是什么

js
小億
138
2023-12-15 00:00:29
欄目: 編程語言

在JavaScript中,有幾種格式化時間的方法,以下是一些常用的方法:

  1. 使用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)
  1. 使用toISOString()方法:
const date = new Date();
const formattedDate = date.toISOString();
console.log(formattedDate); // Output: "2022-05-03T21:45:30.000Z"
  1. 使用第三方庫,如Moment.js:
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"
  1. 手動格式化日期:
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"

這些方法可以根據自己的需求選擇使用,每種方法都有不同的輸出格式。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女