简体   繁体   中英

Calculate time between the current time and a certain day

I am fairly new to (Java) programming and I am trying to build a little Android app that will tell you if it's already weekend or not.

I already got it so far that it can tell you if it's weekend or not, however I also want to show a little countdowntimer in that app until the weekend starts, or ends.

I am unable to think about an Algorithm to calculate the time (in milliseconds) between the current time and the next Saturday (if it's not in a weekend) or Monday if it's a weekend.

I know how to get the current day in the week using the Calendar class, however I get stuck when I try to get the time until the next Saturday or Monday. I can't think about a way to do this.

This might sound like a stupid question but I have really lost my mind in this. Hopefully one of you guys can help me out.

Here's the process, but as a description rather than code, leaving the rest for you as an implementation exercise:

  • Get the current time in milliseconds, and remember it for later
  • Create an appropriate Calendar object
  • Work out the day you're trying to aim for (Saturday or Monday)
  • Work out how many days you need to add to get there (based on the current "day of week" and the day of week you're aiming for), and add that many days
    • As a simpler (but less efficient) alternative: keep adding 1 day until the day of week is correct!
  • Use multiple set calls to get to the right time of day (so set the hour to 0, the minute to 0, the second to 0, the millisecond to 0) - assuming that you're looking for midnight, of course
  • Use getTimeInMillis() to get the point in time you're aiming for
  • Subtract the original value, and the result will be the number of milliseconds you need to wait

One thing to bear in mind is that daylight saving time changes can make things "interesting"... so at the very start of Saturday, there might be 47 or 49 hours before you get to the start of Monday, instead of the normal 48. I'd expect the above algorithm to cope in most cases, but if you "aim" for Sunday you could have an odd situation in Brazil (and a few other places) when you try to get to midnight, as that might be skipped entirely... Time zones are annoying like that.

Additionally, if you can use Joda Time it could make your life simpler.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM