问题
Say I have 2 strings in the following format:
"09/21 10:06AM" "09/21 10:10AM"
How do I find the time difference between these strings, stored as an int? This has to be robust enough to handle situations like 10:59AM and 11:02AM (odd number of minutes in between), 11:59AM and 12:03PM (AM to PM switch) etc. No need to worry about seconds.
Thanks!
回答1:
I would suggest:
- Use Joda Time instead of the built-in API; it's much nicer.
- Parse into LocalDateTime values
Find the difference between them with:
Minutes period = Minutes.minutesBetween(first, second); int minutes = period.getMinutes();
回答2:
- DateFormat.Parse
- Calculate difference between dates.
回答3:
Parse the strings to Date
objects and get the difference between them in milliseconds. Then convert those milliseconds to minutes (divide by 60000 and take the ceiling of the result).
回答4:
If there is a switch to daylight savings the difference can be an hour more on one day than another.
It best to use a library which does this already. JodaTime is best, but SimpleDateFormat and Date will probably do what you need.
回答5:
- Convert the 2 Strings to Dates.
- Subtract one from the other.
- Multiply the result by 1440 (Number of minutes in a day).
- Round the result to an Integer.
Let me know if it works :)
来源:https://stackoverflow.com/questions/7501311/difference-between-minutes