Calculate time difference in Cocoa

后端 未结 4 863
逝去的感伤
逝去的感伤 2021-02-04 08:53

I have got two timevalues in the format: %H%M%S (E.G.161500)

These values are text-based integers.

Is there a simple function in Cocoa that calculates the diffe

4条回答
  •  爱一瞬间的悲伤
    2021-02-04 09:18

    I would create an NSFormatter subclass to parse time values in that format from input data (you can put one on a text field to automatically convert user input, or use it to parse from a data source in code). Have it return the combined number of seconds as an NSTimeInterval (double representing seconds) wrapped in an NSNumber. From there it's easy to subtract the difference, and display it using the same NSFormatter class you created. In both parsing and displaying values, you're the one responsible to write code converting from seconds to hours:minutes:seconds or whatever format you like. You could also convert these values to an NSDate like mouviciel mentioned, if it makes sense for your application. Just keep in mind you're always going to be storing the time difference from a reference date, usually Jan 1st 1970 (NSDate has methods to do this for you).

提交回复
热议问题