提示
本文主要介绍 JavaScript 日期与时间的使用。@ermo
# 日期与时间
js 中日期对象为 Date
,同样是使用 new
关键字进行创建日期对象。
var now = new Date();
console.log(now);
打开浏览器控制台,输出:
Thu Nov 10 2022 14:45:57 GMT+0800 (中国标准时间)
# 常用方法
日期的常用方法分为2类,一类是 setXxx,一类是 getXxx,前者为赋值,后者为获取值。
先来看 getXxx 这一类方法。
方法名 | 作用 |
---|---|
getFullYear() | 获取年份,取值为4位数字 |
getMonth() | 获取月份,取值为0~11的整数 |
getDate() | 获取日,取值为1~31的整数 |
getHours() | 获取小时,取值为0~23整数 |
getMinutes() | 获取分钟,取值为0~23整数 |
getSeconds() | 获取秒,取值为0~59整数 |
console.log("getFullYear=" + now.getFullYear()); // 获取年份,取值为4位数字
console.log("getMonth=" + (now.getMonth() + 1)); // 获取月份,取值为0~1的整数
console.log("getDate=" + now.getDate()); // 获取日,取值为1~31整数
console.log("getHours=" + now.getHours()); // 获取小时,取值为0~23整数
console.log("getMinutes=" + now.getMinutes()); // 获取分钟,取值为0~59整数
console.log("getSeconds=" + now.getSeconds()); // 获取秒,取值为0~59整数
输出
getFullYear=2022
getMonth=11
getDate=15
getHours=15
getMinutes=48
getSeconds=37
接下来看 setXxx 这一类方法。
方法名 | 作用 |
---|---|
setFullYear() | 设置年、月、日,年必填 |
setMonth() | 设置月、日,月必填 |
setDate() | 设置日 |
setHours() | 设置时、分、秒、毫秒,时必填 |
setMinutes() | 设置分、秒、毫秒,分必填 |
setSeconds() | 设置秒、毫秒,秒必填 |
var myDate = new Date();
myDate.setFullYear(2022, 10, 11); // 设置年、月、日,年必填
console.log(myDate);
myDate.setMonth(11, 12); // 设置月、日,月必填
console.log(myDate);
myDate.setDate(11); // 设置日
console.log(myDate);
myDate.setHours(10, 10, 10, 10); // 设置时、分、秒、毫秒,时必填
console.log(myDate);
myDate.setMinutes(11, 11, 11); // 设置分、秒、毫秒,分必填
console.log(myDate);
myDate.setSeconds(12, 12); // 设置秒、毫秒,秒必填
console.log(myDate);
输出
Fri Nov 11 2022 15:48:37 GMT+0800 (中国标准时间)
Mon Dec 12 2022 15:48:37 GMT+0800 (中国标准时间)
Sun Dec 11 2022 15:48:37 GMT+0800 (中国标准时间)
Sun Dec 11 2022 10:10:10 GMT+0800 (中国标准时间)
Sun Dec 11 2022 10:11:11 GMT+0800 (中国标准时间)
Sun Dec 11 2022 10:11:12 GMT+0800 (中国标准时间)