Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
276 views
in Technique[技术] by (71.8m points)

android - Display days, hours, minutes in between 2 dates in java

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"

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?

Edit: my application will only be used in 1 time zone ie. EST, so I do not have to worry about time zone correction

Edit: 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);

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...