在java的日期2之间显示天,小时,分钟 [英] Display days, hours, minutes in between 2 dates in java
问题描述
我需要在未来的格式天指定日期之间显示一个倒数计时器现在:小时:分钟。
因此,例如结束日期是12月4日1:30 PM 2013年和现在它是12月3日下午12:30 2013年,我的TextView(或任何其它视图)应该显示时间remaning第1天:1小时:0分钟
I need to display a countdown timer between a specified date in the future and now in the format Days:Hours:Minutes. So for example the end date is 4th december 1:30 PM 2013 and right now it is 3rd december 12:30 PM 2013, my textView (or any other view) should show "Time remaning 1 day: 1 hours: 0 minutes"
我不想使用乔达时库,它由约4.1 MB增加了我的应用程序的大小,我需要在我的应用程序中使用的日期/时间功能只有一次。
我使用Java提供日历API,我无法实现这个'定时'/'倒计时'功能
I do not want to use joda-time library as it increases my applications size by about 4.1 MB and I need to use the date/time feature only once in my application. I am using the calendar API provided by java and I cannot implement this 'timer'/'countdown timer' functionality
任何想法,我应该如何实现呢?
Any idea how I should implement this?
编辑:我的应用程序将仅在1时区,即可以使用。 EST,所以我不担心时区的修正
my application will only be used in 1 time zone ie. EST, so I do not have to worry about time zone correction
编辑:我至今尝试过,得到了2个日历的几个月
What I have tried so far, get the months of the 2 calendar
cal1.get(Calendar.MONTH); //to get the month
cal2.get(Calendar.MONTH);
cal1.get(Calendar.DAY_OF_MONTH); //to get the day
cal2.get(Calendar.DAY_OF_MONTH);
cal1.get(Calendar.HOUR_OF_DAY); //to get the hour in 24 hours
cal2.get(Calendar.HOUR_OF_DAY);
cal1.get(Calendar.MINUTE); //to get the minutes
cal2.get(Calendar.MINUTE);
cal1.get(Calendar.SECOND); //to get seconds
cal2.get(Calendar.SECOND);
现在我减去了几个月,如果是0,那么我知道,不同的是不到1个月,同样地,我减去天,小时,分钟。然而,这并不给我一个准确的结果。示例 - 今天7月6日凌晨4点到2013年,结束日期7月7日凌晨3点到2013年,根据我的算法,它会说剩余时间 1天-1个小时并我运行一个计时器来执行这个任务每第二个
now I subtract the months, if it is 0 then I know that the difference is less than 1 month, similarly I subtract days, hours, minutes. However that doesnt give me an accurate result. Example - today 6th July 4 AM 2013, end date 7th July 3 AM 2013, according to my algorithm it will say time left is 1 day and -1 hours and I run a timer to execute this task every second
我需要一个更好的算法和更好的方式来显示它,我在UI线程上一次又一次地这样做同样的任务可能会导致落后,我觉得
I need a better algorithm and a better way to display it, I am doing this same task again and again on the UI thread which may cause lag I feel
推荐答案
我猜你有两个 java.util.Date
要比较的对象。首先,你想有一些那种被每N秒执行定时器。 Handler.postDelayed()
作品就好了点。每次执行时,您可以使用 timeMs = futureDate.getTime() - System.currentTimeMillis的()
。这使您可以在毫秒秒的时间差。那么你只需要将其转换为所需的格式:如 =秒timeMs / 1000%60
。
I guess you have two java.util.Date
objects to compare. First you wanna have some kind of timer that gets executed every N seconds. Handler.postDelayed()
works just fine for that. Every time it executes, you use timeMs = futureDate.getTime() - System.currentTimeMillis()
. This gives you the time difference in milli seconds. Then you only need to convert this to the desired format: e.g. seconds = timeMs / 1000 % 60
.
这篇关于在java的日期2之间显示天,小时,分钟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!