// 将年月日转换为时间戳的示例代码
// 定义一个函数,接受年、月、日作为参数
function getTimestamp(year, month, day) {
// 创建一个新的 Date 对象,注意月份是从 0 开始计数的(0 表示 1 月)
const date = new Date(year, month - 1, day);
// 使用 getTime() 方法获取时间戳(以毫秒为单位)
return date.getTime();
}
// 示例调用
const year = 2023;
const month = 10;
const day = 5;
const timestamp = getTimestamp(year, month, day);
console.log(timestamp); // 输出时间戳
// 如果需要将时间戳转换为秒级别的时间戳(通常用于 Unix 时间戳),可以除以 1000
const unixTimestamp = Math.floor(timestamp / 1000);
console.log(unixTimestamp); // 输出 Unix 时间戳
Date
对象用于表示日期和时间。创建 Date
对象时,月份是从 0 开始计数的,因此在传入月份时需要减去 1。getTime()
方法返回从 1970 年 1 月 1 日 00:00:00 UTC 到当前日期对象的时间差(以毫秒为单位),这就是我们常说的时间戳。Math.floor()
去掉小数部分。上一篇:js 数组 reduce
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站