我总是在减去时间时得到0

问题描述 投票:-3回答:4

所以我正在制作一个获取2个时间字符串并减去它们的应用程序,所以我可以获得经过的时间,由于某种原因它总是返回0,请帮帮我。

这是我正在使用的代码

    static String TimeIn(){
    SimpleDateFormat format= new SimpleDateFormat("hh:mm:ss");
    Date time= Calendar.getInstance().getTime();
    a=format.format(time);
    return a;
}
static String TimeOut(){
    SimpleDateFormat format= new SimpleDateFormat("hh:mm:ss");
    Date time= Calendar.getInstance().getTime();
    b=format.format(time);
    return b;
}
static long Duration() throws ParseException{
    String a=TimeIn();
    String b=TimeOut();
SimpleDateFormat format = new SimpleDateFormat("hh:mm:ss");
Date date1 = format.parse(a);
Date date2 = format.parse(b);
long dur = date2.getTime() - date1.getTime();
return dur/1000;
}
static String a;
static String b;
java
4个回答
0
投票

您的代码获得两次。

之后,您计算出差值并将其除以1000。

问题是时间以毫秒为单位,为long值。

时间可以在不到一毫秒的时间内计算,因此可能等于long无法存储小数。

此外,除以1000会导致更糟,因为它会擦除所有差异[[小于一秒。

换句话说,如果结果不应该是TimeIn,则TimeOut0的调用之间的时间差必须至少为一秒钟。

[

Note

]按照惯例,方法名称在Java中应以小写字母开头。

0
投票
您在另一测量之后立即进行测量。

请考虑以下情形:

String a = TimeIn(); Thread.sleep(2000L); String b = TimeOut();

然后输出为:

2


0
投票
[似乎您在TimeIn之后立即致电TimeOut。它们在不到一秒钟的时间内执行,因此您的日期(仅精确到秒)是相同的。将Thread.sleep(100000)放在中间可打印正确的持续时间:

// throw Exception for brevity static long Duration() throws Exception{ String a=TimeIn(); Thread.sleep(10000); String b=TimeOut(); // ... }

对于更精确的持续时间测量,请使用System.currentTimeMillis()甚至System.nanoTime()

long then = System.currentTimeMillis(); // do stuff long duration = System.currentTimeMillis() - then;

这将为您提供时间(以毫秒为单位)。在此示例中,Duration()在30-50毫秒内运行同样,方法通常以小写字母开头,例如duration()timeIn()

0
投票
TimeIn()和TimeOut()的时差执行可以忽略不计。我们可以使用Thread.sleep();

class Demo { public static void main(String[] args) throws ParseException, InterruptedException { System.out.println(Duration()); } static String TimeIn() throws InterruptedException { SimpleDateFormat format= new SimpleDateFormat("hh:mm:ss:SSS"); Date time= Calendar.getInstance().getTime(); Thread.sleep(2000); a=format.format(time); return a; } static String TimeOut(){ SimpleDateFormat format= new SimpleDateFormat("hh:mm:ss:SSS"); Date time= Calendar.getInstance().getTime(); b=format.format(time); return b; } static long Duration() throws ParseException, InterruptedException { String a=TimeIn(); String b=TimeOut(); SimpleDateFormat format = new SimpleDateFormat("hh:mm:ss:SSS"); Date date1 = format.parse(a); Date date2 = format.parse(b); long dur = date2.getTime() - date1.getTime(); return dur/1000; } static String a; static String b; }

© www.soinside.com 2019 - 2024. All rights reserved.