溫馨提示×

JavaScript日期獲取方法有哪些

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

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

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

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

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