素材巴巴 > 程序开发 >

js 时间戳差 转换成 年月日天数

程序开发 2023-09-03 12:09:05

想做脚本的可用时间的html显示,但是js并没有封装这样的工具类

在csdn搜了一下,有个大佬已经做好了

https://blog.csdn.net/qq_26744901/article/details/51735988

但是bug。我是直接在控制台调试的,简单方便

问题出来了,传入的时间戳小于1000,结果就是是负数,年数还很大。

悲剧,还是得细细的看代码。

出的问题很简单,

输入的时间戳和一个很大的分界线时间戳,做除法会是小数(因为传入的时间戳很小),小数再parseInt就会变成负数

js不和java一样,java是强类型的编程语言,整数除整数一定是整数,js不一样,整数除整数会是小数,所以需要先取整。这位大哥估计是写java没太注意,哈哈

改进一下

加上取整就好了,忽略掉小数部分

完整代码贴上

function getdate(period) {var yearLevelValue = 365 * 24 * 60 * 60 * 1000;var monthLevelValue = 30 * 24 * 60 * 60 * 1000;var dayLevelValue = 24 * 60 * 60 * 1000;var hourLevelValue = 60 * 60 * 1000;var minuteLevelValue = 60 * 1000;var secondLevelValue = 1000;function getDifference(period) {/*******计算出时间差中的年、月、日、天、时、分、秒*******/var year = parseInt(getYear(period));var month = parseInt(getMonth(period - year * yearLevelValue));var day = parseInt(getDay(period - year * yearLevelValue - month * monthLevelValue));var hour = parseInt(getHour(period - year * yearLevelValue - month * monthLevelValue - day * dayLevelValue));var minute = parseInt(getMinute(period - year * yearLevelValue - month * monthLevelValue - day * dayLevelValue - hour * hourLevelValue));var second = parseInt(getSecond(period - year * yearLevelValue - month * monthLevelValue - day * dayLevelValue - hour * hourLevelValue - minute * minuteLevelValue));var result = "";if (year != 0)result = result + year + "年";if (month != 0)result = result + month + "月";if (day != 0)result = result + day + "天";result = result + hour + "时" + minute + "分" + second + "秒";function getYear(period) {//Math.floor()return Math.floor(parseInt(period) / yearLevelValue);}function getMonth(period) {return Math.floor(parseInt(period) / monthLevelValue);}function getDay(period) {return Math.floor(parseInt(period) / dayLevelValue);}function getHour(period) {return Math.floor(parseInt(period) / hourLevelValue);}function getMinute(period) {return Math.floor(parseInt(period) / minuteLevelValue);}function getSecond(period) {return Math.floor(parseInt(period) / secondLevelValue);}return result;}return getDifference(period);}

 


标签:

素材巴巴 Copyright © 2013-2021 http://www.sucaibaba.com/. Some Rights Reserved. 备案号:备案中。