日期对象是我们在js中常用的内置对象,我们可以使用它进行一系列和日期相关的操作。
一、创建时间日期对象
利用new方法创建Date的日期对象
var date3 = new Date('Wed Jan 27 2017 12:00:00 GMT+0800 (中国标准时间)');
var date4 = new Date(2017, 1, 27);
new Date("2017/09/06 09:00:00")
new Date()
二、获取时间日期
可以通过Date.getTime()来进行
当前时间:2018年6月13日6时4分30秒。
• getTime(),获取时间戳,返回毫秒数,//setTime(),以毫秒设置日期,会改变整个日期。
• getFullYear(),返回年份,以4位数表示。//setFullYear(),设置日期的年月,必须以4位数表示。
• getMonth(),返回月份,0~11。
• getDate(),返回天数,1~31。
• getDay(),返回星期几,0~6。
• getHours(),返回小时数,0~23。
• getMinutes(),返回分钟数,0~59。
• getSeconds(),返回秒数,0~59。
• getMilliseconds(),返回毫秒数。
const date = new Date()
console.log(date.getFullYear()) // 2023 完整年份
console.log(date.getMonth()) // 0-11 0表示1月
console.log(date.getDate()) // 日
console.log(date.getHours()) // 时
console.log(date.getMinutes()) // 分
console.log(date.getSeconds())
三、创建一个自定义日期时间
const d = new Date('2024-1-1')
const d = new Date(2024, 0, 1)
注意:当我们使用数字格式时,月份是从0开始计算的,因此0才是一月