Difference between minutes

爷,独闯天下 提交于 2020-01-17 03:54:06

问题


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:


  1. DateFormat.Parse
  2. 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:


  1. Convert the 2 Strings to Dates.
  2. Subtract one from the other.
  3. Multiply the result by 1440 (Number of minutes in a day).
  4. Round the result to an Integer.

Let me know if it works :)



来源:https://stackoverflow.com/questions/7501311/difference-between-minutes

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!