Java时间戳减法

时间:2017-02-11 17:59:40

标签: java json timestamp java-time

我有一个时间戳作为来自Json的字符串,形式为11/02/2017 17:25:20,作为actualArrivalTime,11/02/2017 17:25:22作为actualScheduledTime。我想通过减去两个时间戳来计算delayTime来得到差值,在这种情况下,这将是+2或-2秒。

4 个答案:

答案 0 :(得分:1)

首先需要将字符串解析为日期 - 在您的情况下,LocalDateTime class似乎是合适的。然后,您可以计算差异:

String actualArrivalTime = "11/02/2017 17:25:20";
String actualScheduledTime = "11/02/2017 17:25:22";

DateTimeFormatter fmt = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss");
LocalDateTime arrival = LocalDateTime.parse(actualArrivalTime, fmt);
LocalDateTime scheduled = LocalDateTime.parse(actualScheduledTime, fmt);

long seconds = ChronoUnit.SECONDS.between(arrival, scheduled);
System.out.println("Time difference in seconds: " + seconds);

答案 1 :(得分:0)

var actualArrivalTime = new Date("11/02/2017 17:25:20");
var actualScheduledTime = new Date("11/02/2017 17:25:22");

var delayTime =  (actualArrivalTime - actualScheduledTime) / 1000; //-2

根据您需要的顺序,您可以切换两个变量。

答案 2 :(得分:0)

var date1=new Date("11/02/2017 17:25:20");
var date2=new Date("11/02/2017 17:25:22");

var diff = Math.abs(date1 - date2);
console.log(diff/1000);

答案 3 :(得分:0)

试试这个:

var arrivalTime = new Date("11/02/2017 17:25:20");
var scheduledTime = new Date("11/02/2017 17:25:22");

var diff =  arrivalTime.getTime() - scheduledTime.getTime();
var diffInMs = (diff/1000);