You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript中为何需将毫秒数除以1才能转换为有效Date对象?

为什么字符串时间戳直接用new Date()无效,除以1就可以?

这个问题其实和JavaScript的Date构造函数对不同类型参数的处理逻辑有关,我来给你拆解清楚:

核心原因:参数类型不同,Date的处理逻辑完全不一样

1. 当传入字符串类型的纯数字(比如你的"1383262200000")

new Date(board.resultsbox.value)里,board.resultsbox.value是字符串格式的数字。Date构造函数对字符串参数的处理规则是:仅能解析符合特定日期格式的字符串(比如ISO 8601格式"2023-10-05T14:48:00"、美式格式"MM/DD/YYYY"等)。而纯数字组成的字符串并不在它的合法解析范围内,所以会返回Invalid Date。

2. 当传入数字类型的时间戳(比如1383262200000)

board.resultsbox.value/1这个操作其实是做了类型转换:因为除法是算术运算,JavaScript会自动把字符串形式的数字转换成真正的Number类型。此时new Date()接收的是数字参数,它会把这个数字当作从1970年1月1日00:00:00 UTC开始计算的毫秒级时间戳,自然就能正确生成对应的日期了。

其他等价的类型转换方式

除了/1,你还可以用这些方式把字符串转成数字,效果完全一样:

  • Number(board.resultsbox.value)
  • +board.resultsbox.value
  • parseInt(board.resultsbox.value, 10)

你的代码验证

JavaScript代码:

d1 = new Date(board.resultsbox.value/1); 
d2 = new Date(board.resultsbox.value); 
board.resultsbox1.value = d1; // Fri Nov 01 2013 00:30:00 GMT+0100 (CET)
board.resultsbox2.value = d2; // Invalid Date

HTML代码:

<html>
<head>
<title>calculator based on javascript.</title>
</head>
<body>
<form name="board" id="board">
<input type="input" id="resultsbox" value="1383262200000">
<input type="input" id="resultsbox1">
<input type="input" id="resultsbox2">
</form>
<input type="button" onclick=" d1=new Date(board.resultsbox.value/1); d2=new Date(board.resultsbox.value); board.resultsbox1.value=d1; board.resultsbox2.value=d2;" style="height: 80px;" value="=">
</body>
</html>

内容的提问来源于stack exchange,提问作者pats

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 06:47:04