我需要两个时间戳的差异,以秒为单位。但是当计算它错误地给出了。如何根据两个时间戳的差异计算秒数?提前谢谢。
下面,
First timestamp = 20180104113612
Second timestamp = 20180104113954
Difference = First timestamp - Second timestamp
结果为342.但实际上它应该是222.所以请任何人帮助找到差异的秒数?
答案 0 :(得分:0)
试试这个
let startDate = new Date();
let endDate = new Date();
let differenceInSecond = (endDate - startDate) / 1000; //since it's originally in milliseconds
答案 1 :(得分:0)
您需要解析日期中的年,月,日,小时,分钟和秒,然后创建一个date
对象,然后减去两个日期以获得差异。
var firstTimestamp = 20180104113612,
secondTimestamp = 20180104113954,
getDate = (time) => {
time = time.toString();
var year = time.substring(0,4),
month = time.substring(4,6),
day = time.substring(6,8),
hour = time.substring(8,10),
minutes = time.substring(10,12),
seconds = time.substring(12,14);
return new Date(year, month, day, hour, minutes, seconds);
},
getTimeDifference = (firstTime, secondTime) => {
return Math.floor((getDate(secondTime) - getDate(firstTime))/1000);
};
console.log(getTimeDifference(firstTimestamp, secondTimestamp));

答案 2 :(得分:0)
首先,您必须以适当的格式格式化您的日期。 " 2018-01-04T11:36:12&#34 ;;
格式化你可以使用像这样的函数
function getFormat(dateString) {
var txt = dateString.slice(0, 4)
+ "-"
+ dateString.slice(4, 6)
+ "-"
+dateString.slice(6,8)
+"T"
+dateString.slice(8,10)
+":"
+dateString.slice(10,12)
+":"
+dateString.slice(12,14);
return txt;
}
然后将其转换为javascript Date对象。
const First_timestamp = 20180104113612;
const Second_timestamp = 20180104113954;
const FirstDate = new Date(getFormat(First_timestamp.toString()));
const SecondDate = new Date(getFormat(Second_timestamp.toString()));
const TimeDiffInSeconds = (SecondDate.getTime() - FirstDate.getTime()) / 1000;