js时间对象常用方法

  • 获取当前时间对象
var date = new Date()

1、常用获取对应时间段对象的几种方法

// 所有浏览器和设备都兼容
new Date(year, month, day, Hours, minutes, seconds)

// 下面两个方式可能有些设备不一样
// 使用 / 分割年月日
new Date("year/month/day hours:minutes:seconds")
// 使用 - 分割年月日
new Date("year-month-day hours:minutes:seconds")

2、获取本地日期字符串

new Date().toLocaleString()
// 返回 '2022/8/2 14:31:17'

3、获取日期方法

// 年
new Date().getFullYear()
// 月 - 返回 0(1月) - 11(12月)
new Date().getMonth()
// 日
new Date().getDate()

// 时
new Date().getHours()
// 分
new Date().getMinutes()
// 秒
new Date().getSeconds()

// 星期几 - 返回 0-6,0(周日) - 6(周六)
new Date().getDay()

// 获取时间戳
new Date().getTime()

4、设置时间

// 年
new Date().setFullYear( year )
// 月 - month = 0(1月) - 11(12月)
new Date().setMonth( month )
// 日
new Date().setDate( day )

// 时
new Date().setHours( hours )
// 分
new Date().setMinutes( minutes )
// 秒
new Date().setSeconds( seconds )
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。