所以我正在制作一个获取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;
您的代码获得两次。
之后,您计算出差值并将其除以1000。
问题是时间以毫秒为单位,为long
值。
时间可以在不到一毫秒的时间内计算,因此可能等于long
无法存储小数。
此外,除以1000会导致更糟,因为它会擦除所有差异[[小于一秒。
换句话说,如果结果不应该是TimeIn
,则TimeOut
和0
的调用之间的时间差必须至少为一秒钟。[
Note
]按照惯例,方法名称在Java中应以小写字母开头。请考虑以下情形:
String a = TimeIn();
Thread.sleep(2000L);
String b = TimeOut();
然后输出为:2
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()
。
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;
}