javascript - javascript中的 Date(d.getTime()) 和 new Date(d.getTime()) 有什么区别?
问题描述
我一直在处理日期并意识到这两个命令Date(d.getTime())
是new Date(d.getTime())
不同的。
当我运行这个片段时:
var d = new Date(2016,11,12);
console.log(Date(d.getTime()));
console.log(new Date(d.getTime()));
我有这个结果:
(index):68 Thu Dec 12 2019 18:02:41 GMT-0300 (Horário Padrão de Brasília)
(index):69 Mon Dec 12 2016 00:00:00 GMT-0200 (Horário de Verão de Brasília)
为什么它们不同?
我试图找到一些答案,但我没有找到。这些是我经历过的一些参考资料:
Date(dateString) 和 new Date(dateString) 之间的区别
解决方案
Date
获取window
/globalDate
对象,new Date()
创建一个新的静态Date
对象。当您创建一个时,new Date()
您会及时冻结它的价值。
使用时Date()
,它会返回当前日期的字符串表示形式,就像调用new Date().toString()
.
根据您的代码:
// this is a new date, Dec. 12, 2016
var d = new Date(2016,11,12);
// this returns the time value of Date d
d.getTime()
// Calling Date as a function just returns a string for
// the current date, arguments are ignored
console.log(Date(d.getTime()));
// this creates a new date based on d's time value
console.log(new Date(d.getTime()));
推荐阅读
- python - 用非空字符串值随机填充列的 NaN 值
- angular - 从端口 4200 到 Api Net Core 2.1 后端使用的任何端口的 Angular 8 (ECONNRESET) 代理错误
- c++ - 如何在 CUDA 中使用 Eigen?
- android - 在 Android (Android X) 不兼容上运行 Flutter 应用程序时出错
- google-chrome - chrome 扩展 mv3 - 模块化服务工作者 js 文件
- antlr - ANTLR:对 bash 文件进行词法分析,尤其是 heredoc
- python - Selenium,Python:如何设置 Firefox 驱动程序?
- javascript - 如何检查我上传的文件是否与我已有的文件名相同?
- html - 如何修改我的 CSS 以使用 Flexbox 创建大小相等的卡片组件?
- c# - Nest在查询中将字段的第一个字母转换为小写