JavaScript使用new Date()拆分字段重建时间对象时间不一致问题咨询
时间偏差的核心原因
参数顺序错位是分钟级随机差的根源
这个偏差完全不是Date对象的底层设计问题,纯粹是传参顺序错位导致的。
JavaScript的new Date()本地时间构造器,传入多参数时的固定顺序为:
- 年(完整4位年份)
- 月份(0基取值,和
getMonth()返回值一致) - 当月日期
- 小时(24小时制)
- 分钟
- 秒
- 毫秒
对照你写的传参代码:
new Date(currentYear, currentMonth, currentDay, currentHour, currentMinutes, currentMiliseconds)
你在传入完分钟值后,直接把提取的毫秒值放到了秒的参数位,完全跳过了秒的传参位置。
由于毫秒值的取值范围是0~999,把这个值当秒传给构造器时,构造器会自动按60进制做进位换算:比如提取到的毫秒是456,就会被换算成7分36秒,直接叠在你提取的分钟值上。
每次运行时代码生成的毫秒值是随机的,最终的时间偏差自然就会在0秒到16分39秒之间无规律波动,和你观察到的现象完全吻合。
微小时序差属于正常现象
就算修正了参数顺序,逐行提取时间字段的过程本身需要消耗极短的执行时间(通常在微秒到毫秒级),这部分差值不会达到分钟级别,但也无法做到两个时间实例100%完全相等。
修正后的可正常运行代码
补充提取秒值,按正确顺序传参即可:
var getDate = new Date(); var currentYear = getDate.getFullYear(); var currentMonth = getDate.getMonth(); var currentDay = getDate.getDate(); var currentHour = getDate.getHours(); var currentMinutes = getDate.getMinutes(); // 新增:提取原时间的秒值 var currentSeconds = getDate.getSeconds(); var currentMiliseconds = getDate.getMilliseconds(); // 按正确顺序传参:年、月、日、时、分、秒、毫秒 var currentTime = new Date(currentYear, currentMonth, currentDay, currentHour, currentMinutes, currentSeconds, currentMiliseconds); console.log(getDate.toString()); console.log(currentTime.toString());
内容的提问来源于stack exchange,提问作者George Smith
相关产品推荐
相关产品推荐

