日期对象

概念

日期对象:用来表示时间的对象

作用:可以得到当前系统时间

实例化

在代码中发现了 new 关键字时,一般将这个操作称为实例化

有 4 种方法创建新的日期对象:

  • new Date()
  • new Date(year, month, day, hours, minutes, seconds, milliseconds)
  • new Date(milliseconds)
  • new Date(date string)
//创建时间日期对象
const n1 = new Date()//创建当前时间
const n2 = new Date(2222, 2, 2, 6, 6, 6)//创建指定时间
const n3 = new Date(100000000000)//创建指定时间
const n4 = new Date('2222-2-2 6:6:6')//创建指定时间

日期对象方法

方法 描述
getFullYear() 获取四位的年份(yyyy)
getMonth() 获取月份(0-11)
getDate() 以数值返回天(1-31)
getHours() 获取小时(0-23)
getMinutes() 获取分钟(0-59)
getSeconds() 获取秒(0-59)
getMilliseconds() 获取毫秒(0-999)
getDay() 以数值获取周名(0-6 0:星期天)
getTime() 获取时间(从 1970 年 1 月 1 日至今的毫秒数)
// 创建时间日期对象
const date = new Date()//创建当前时间
// 方法
const year = date.getFullYear()//获取年份(四位数)
const month = date.getMonth()//获取月份 (0~11)
const date1 = date.getDate()//获取月份的某一天(1~31)
const hour = date.getHours()//获取小时(0~23)
const minute = date.getMinutes()//获取分钟(0~59)
const second = date.getSeconds()//获取秒(0~59)
const millisecond = date.getMilliseconds()//获取毫秒(0~999)
const day = date.getDay()//获取星期(0~6 0:星期天)
console.log(`
年:${year}
月:${month}
日:${date1}
时:${hour}
分:${minute}
秒:${second}
毫秒:${millisecond}
星期:${day}
`)

时间戳

概念

是指1970年01月01日00时00分00秒起至现在的毫秒数,它是一种特殊的计量时间的方式

获取时间戳

  1. 使用 getTime() 方法

  2. 简写 +new Date()

  3. 使用 Date.now()

    无需实例化

    但是只能得到当前的时间戳, 而前面两种可以返回指定时间的时间戳

posted @   丫丫learning  阅读(155)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· 没有源码,如何修改代码逻辑?
· PowerShell开发游戏 · 打蜜蜂
· 在鹅厂做java开发是什么体验
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战
点击右上角即可分享
微信分享提示