温馨提示×

JavaScript日期获取方法有哪些

小亿
92
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