我正在创建一个倒数计时器,我有 2 个日期(现在和结束日期),格式为 mm:dd:yyyy:hour:minute:sec 我需要显示剩余时间,实际上是
结束日期:时间 - 当前约会时间
我想以毫秒为单位转换两个日期,减去然后将它们转换回日期,但这似乎太麻烦了如何在java中有效地实现这一点?
我正在创建一个倒数计时器,我有 2 个日期(现在和结束日期),格式为 mm:dd:yyyy:hour:minute:sec 我需要显示剩余时间,实际上是
结束日期:时间 - 当前约会时间
我想以毫秒为单位转换两个日期,减去然后将它们转换回日期,但这似乎太麻烦了如何在java中有效地实现这一点?
Let the joda-time
framework do it for you
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());
Prints
2013-02-13T14:45:42.000-05:00
2013-02-13T14:45:49.000-05:00
7000
So you parse your date Strings into DateTime
objects and use the Duration
object to calculate the time difference in some time unit.
You can alternatively use an Interval
or Period
object (depending on the precision required)
System.out.println(duration.toPeriod().get(DurationFieldType.seconds()));
You state
I thought of converting both dates in milliseconds, subtracting and then converting them back to dates
Why would you have to convert them back? You already have them. You're just interested in the time between.
日历直到 = Calendar.getInstance();
直到.set("YYYY","DD","HH","MM","SS");
获取时间差异(直到);
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;
}