JavaScript 中将时间戳转换为日期
本教程将解释我们如何在 JavaScript 中把 Unix 时间戳转换为日期。Unix 时间戳是自 1970 年 1 月 1 日 00:00:00UTC 以来经过的时间,用秒来表示。
JavaScript Date
对象包含了自 1970 年 1 月 1 日 00:00:00 UTC 以来经过的时间,以毫秒为单位。
在 JavaScript 中把 Unix 时间戳转换为 Date
当我们使用 new Date()
从 Date()
类中创建一个新的对象时,它会返回创建时的时间,单位为毫秒。如果我们需要在特定的时间点从 Date
类中获取一个对象,我们可以将 epoch 时间戳传递给该类的构造函数。
var timestamp = 1607110465663
var date = new Date(timestamp);
console.log(date.getTime())
console.log(date)
输出:
1607110465663
2020-12-04T19:34:25.663Z
Date
类提供了许多方法来表示 Date
的首选格式,如:
var timestamp = 1607110465663
var date = new Date(timestamp);
console.log(
'Date: ' + date.getDate() + '/' + (date.getMonth() + 1) + '/' +
date.getFullYear() + ' ' + date.getHours() + ':' + date.getMinutes() + ':' +
date.getSeconds());
输出:
Date: 4/12/2020 19:34:25
由于 JavaScript Date
时间戳是以毫秒为单位,而 Unix 时间戳是以秒为单位,所以我们可以将 Unix 时间戳乘以 1000 来转换为 JavaScript 时间戳。如果 Unix 时间戳是 1607110465
,那么 JavaScript 时间戳就是 1607110465000
。
下面的例子演示了我们如何将 Unix 时间戳转换为 JavaScript Date
时间戳。
var unixTimestamp = 62678980
var date = new Date(unixTimestamp * 1000);
console.log('Unix Timestamp:', unixTimestamp)
console.log('Date Timestamp:', date.getTime())
console.log(date)
console.log(
'Date: ' + date.getDate() + '/' + (date.getMonth() + 1) + '/' +
date.getFullYear() + ' ' + date.getHours() + ':' + date.getMinutes() + ':' +
date.getSeconds());
输出:
Unix Timestamp: 62678980
Date Timestamp: 62678980000
Mon Dec 27 1971 12:49:40 GMT+0200 (Eastern European Standard Time)
Date: 27/12/1971 12:49:40
相关文章
Do you understand JavaScript closures?
发布时间:2025/02/21 浏览次数:108 分类:JavaScript
-
The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.
Do you know about the hidden traps in variables in JavaScript?
发布时间:2025/02/21 浏览次数:178 分类:JavaScript
-
Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av
How much do you know about the Prototype Chain?
发布时间:2025/02/21 浏览次数:150 分类:JavaScript
-
The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start
用 jQuery 检查复选框是否被选中
发布时间:2024/03/24 浏览次数:102 分类:JavaScript
-
在本教程中学习 jQuery 检查复选框是否被选中的所有很酷的方法。我们展示了使用直接 DOM 操作、提取 JavaScript 属性的 jQuery 方法以及使用 jQuery 选择器的不同方法。你还将找到许多有用的
jQuery 中的 Window.onload 与 $(document).ready
发布时间:2024/03/24 浏览次数:180 分类:JavaScript
-
本教程演示了如何在 jQuery 中使用 Window.onload 和 $(document).ready 事件。