溫馨提示×

JavaScript日期獲取方法有哪些

小億
97
2023-10-13 03:23:14
欄目: 編程語言

JavaScript中有多種方法可以獲取日期,以下是一些常用的方法:

  1. 使用Date()構(gòu)造函數(shù)獲取當(dāng)前日期和時間:
const currentDate = new Date();
  1. 使用getFullYear()、getMonth()、getDate()等方法獲取特定日期的年、月、日等信息:
const year = currentDate.getFullYear();
const month = currentDate.getMonth(); // 月份從0開始,0表示一月
const day = currentDate.getDate();
  1. 使用getDay()方法獲取星期幾的數(shù)值(0表示星期日,1表示星期一,以此類推):
const dayOfWeek = currentDate.getDay();
  1. 使用toLocaleString()方法獲取本地化的日期和時間字符串:
const localDateTimeString = currentDate.toLocaleString();
  1. 使用toUTCString()方法獲取UTC格式的日期和時間字符串:
const utcDateTimeString = currentDate.toUTCString();
  1. 使用getTime()方法獲取距離1970年1月1日的毫秒數(shù):
const milliseconds = currentDate.getTime();
  1. 使用第三方庫如Moment.js來進(jìn)行更復(fù)雜的日期操作和格式化:
const formattedDate = moment(currentDate).format('YYYY-MM-DD');

這些只是JavaScript中獲取日期的常用方法,還有其他一些方法可以根據(jù)具體需求使用。

0