js如何获取当前日期

  • 文章介绍
  • 热门推荐
  • 热门内容

如何使用 JavaScript 获取当前日期

方法 1:使用 new Date() 构造函数

new Date() 构造函数返回一个代表当前日期和时间的 Date 对象。

// 创建一个 Date 对象,代表当前日期和时间const currentDate = new Date();

方法 2:使用 Date.now() 方法

Date.now() 方法返回当前时间戳,表示自 Unix 纪元(1970 年 1 月 1 日午夜 UTC)以来的经过的毫秒数。

// 获取当前时间戳const timestamp = Date.now();

获取日期的特定部分

可以使用以下属性和方法从 Date 对象中获取日期的特定部分:

  • getFullYear(): 获取年份
  • getMonth(): 获取月份(0-11 表示 1 月到 12 月)
  • getDate(): 获取日期(1-31)
  • getDay(): 获取星期(0-6 表示星期日到星期六)
  • getHours(): 获取小时
  • getMinutes(): 获取分钟
  • getSeconds(): 获取秒
  • getMilliseconds(): 获取毫秒

示例

// 使用 new Date() 获取当前日期const currentDate = new Date();// 使用 Date.now() 获取当前时间戳const timestamp = Date.now();// 从 Date 对象中获取特定部分const year = currentDate.getFullYear();const month = currentDate.getMonth() + 1; // +1 因为 getMonth() 返回 0-11const day = currentDate.getDate();const hour = currentDate.getHours();const minute = currentDate.getMinutes();const second = currentDate.getSeconds();

以上就是js如何获取当前日期的详细内容,更多请关注css网站其它相关文章!