JavaScript时间对象Date内置构造函数操作实例攻略
JavaScript内置Date
对象表示时间和日期。它使用Unix时间戳度量时间,并支持各种解析、格式化和操作日期时间的方法。在本文中,我们将深入学习Date
对象的使用方法。
创建Date对象
在JavaScript中,可以使用Date()
构造函数创建新的Date
对象。当没有参数时,Date
对象表示当前的日期和时间。
const now = new Date();
console.log(now); // 打印当前日期和时间
Date
对象还可以接受各种参数,用于设置对象表示的时间。例如:年、月、日、小时、分钟、秒、毫秒。
const birthday = new Date(1990, 6, 20); // 1990年7月20日
console.log(birthday);
const christmas = new Date(2021, 11, 25, 0, 0, 0); // 2021年12月25日0时0分0秒
console.log(christmas);
还可以使用UNIX时间戳来创建Date
对象,UNIX时间戳是自1970年1月1日午夜起的秒数。通过这种方法,可以轻松地将Date
对象从字符串转换为数字或反之。
const timestamp = 946684800000; // 2000年1月1日
const newYear = new Date(timestamp);
console.log(newYear);
获取和设置时间值
通过Date
对象,可以获取和设置时间的各个组成部分,例如:年、月、日、小时等。
const now = new Date();
const year = now.getFullYear();
const month = now.getMonth(); // 返回0-11,0表示1月份
const date = now.getDate();
const hours = now.getHours();
const minutes = now.getMinutes();
const seconds = now.getSeconds();
console.log(`${year}-${month + 1}-${date}`); // 前后补0的日期格式
console.log(`${hours}:${minutes}:${seconds}`); // 前后补0的时间格式
其中,getFullYear()
方法返回年份,getMonth()
方法返回月份(0表示1月,11表示12月),getDate()
方法返回日份等。同时也可以使用setFullYear()
、setMonth()
、setDate()
等方法设置时间值。
格式化和解析日期
JavaScript提供了许多方法来格式化和解析日期字符串。其中,toLocaleDateString()
方法返回本地化的日期字符串表示形式。该方法接受参数指定日期格式,例如:"zh-CN"表示中国风格的日期。
const now = new Date();
console.log(now.toLocaleDateString("zh-CN")); // 输出形如"2022/2/15"的日期格式
Date
对象还提供了toString()
和toISOString()
方法分别返回可读的字符串表示形式和ISO格式的字符串表示形式。
const now = new Date();
console.log(now.toString()); // Sun Feb 13 2022 16:34:38 GMT+0800 (中国标准时间)
console.log(now.toISOString()); // 2022-02-13T08:34:38.081Z
Date.parse()
方法允许将日期字符串转换为UNIX时间戳。通常,字符串应采用ISO 8601格式,但该方法还支持其他字符串格式。
const timestamp = Date.parse("2022-02-13T16:34:38.081+08:00");
console.log(timestamp); // 1644740078081
得到时间戳
可以通过getTime()
方法获取UNIX时间戳。
const now = new Date();
const timestamp = now.getTime(); // 返回以1970年1月1日午夜起的毫秒数
console.log(timestamp);
示例说明
以下是两个实际的例子:
// 例1:计算两个日期之间的秒数
const start = new Date("2022-02-13T22:00:00+08:00");
const end = new Date("2022-02-14T02:00:00+08:00");
const diff = (end - start) / 1000; // 转换成秒数
console.log(diff); // 14400
// 例2:验证给定的日期是否是今天
function isToday(date) {
const now = new Date();
return (
date.getDate() === now.getDate() &&
date.getMonth() === now.getMonth() &&
date.getFullYear() === now.getFullYear()
);
}
const today = new Date();
const tomorrow = new Date("2022-02-14");
console.log(isToday(today)); // true
console.log(isToday(tomorrow)); // false
以上是关于JavaScript时间对象Date内置构造函数操作实例的详细攻略。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:JavaScript时间对象Date内置构造函数操作实例 - Python技术站