Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/date/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何创建日期计时器_Java_Date_Countdowntimer - Fatal编程技术网

Java 如何创建日期计时器

Java 如何创建日期计时器,java,date,countdowntimer,Java,Date,Countdowntimer,我正在创建一个倒计时计时器,我有两个日期(现在和结束日期),格式为mm:dd:yyyy:hour:minute:sec,我需要显示剩余的时间,实际上就是 结束日期:时间-当前日期:时间 我曾想过以毫秒为单位转换两个日期,减去后再转换回日期,但这似乎太麻烦了 如何在java中有效地实现这一点?让joda time框架为您完成这一任务 String date = "02:13:2013:14:45:42"; // one of these is your end time String date2

我正在创建一个倒计时计时器,我有两个日期(现在和结束日期),格式为mm:dd:yyyy:hour:minute:sec,我需要显示剩余的时间,实际上就是
结束日期:时间-当前日期:时间

我曾想过以毫秒为单位转换两个日期,减去后再转换回日期,但这似乎太麻烦了
如何在java中有效地实现这一点?

joda time
框架为您完成这一任务

String date = "02:13:2013:14:45:42"; // one of these is your end time
String date2 = "02:13:2013:14:45:49"; // the other gets smaller every time as you approach the end time
// 7 seconds difference

DateTimeFormatter format = DateTimeFormat.forPattern("MM:dd:yyyy:HH:mm:ss"); // your pattern

DateTime dateTime = format.parseDateTime(date);
System.out.println(dateTime);

DateTime dateTime2 = format.parseDateTime(date2);
System.out.println(dateTime2);

Duration duration = new Duration(dateTime, dateTime2);
System.out.println(duration.getMillis());
印刷品

2013-02-13T14:45:42.000-05:00
2013-02-13T14:45:49.000-05:00
7000
因此,您将日期字符串解析为
DateTime
对象,并使用
Duration
对象计算某个时间单位的时差

您也可以使用
间隔
周期
对象(取决于所需的精度)


你说

我想把两个日期都转换成毫秒,减法和减法 然后将它们转换回日期


你为什么要把它们换回来?你已经有了。您只对两者之间的时间感兴趣。

Calendar-until=Calendar.getInstance()

直到.设置(“YYYY”、“DD”、“HH”、“MM”、“SS”)

getTimeDifference(直到)



好。事实上,
java.util.Date
只不过是一个表示毫秒长的包装器。另外,您可能对Joda Time中的某些内容感兴趣。类似的内容可能会有所帮助。我正在将它们转换回日期,因为在我的应用程序中,我希望在日期中显示剩余时间format@AkshatAgarwal请注意,持续时间不是日期,因此,以日期的
hour:minute:seconds…
格式显示它是没有意义的。
Period
对象具有可用于任何时间单位的
get
方法。例如,您可以显示剩余的小时、分钟和秒。@SotiriosDelimanolis事实上,如果您有倒计时,则希望以h:m:s格式显示结果是有意义的。但是您是对的,OP应该使用Duration的getter方法来构建字符串输出;)@没错,在计时器格式中是有意义的,但在带有时区的日期格式中就没有。日期/时间差是一个复杂的过程,需要考虑许多可变因素(不包括夏令时),两个日期之间的距离越远,问题就越严重。相互减去毫秒不会得到非常精确的结果。最好使用专用的库,例如JodaTime-IMHO
System.out.println(duration.toPeriod().get(DurationFieldType.seconds()));
private String getTimeDifference(Calendar until) {
    Calendar nowCal = (Calendar) until.clone();
    nowCal.clear();
    Date nowDate = new Date(System.currentTimeMillis());
    nowCal.setTime(nowDate);
    int sec = until.get(Calendar.SECOND) - nowCal.get(Calendar.SECOND);
    int min = until.get(Calendar.MINUTE) - nowCal.get(Calendar.MINUTE);
    int hrs = until.get(Calendar.HOUR) - nowCal.get(Calendar.HOUR);

    String timeDiff = hrs+":"+min+":"+sec;

    return timeDiff;
}