NSDate: Right way to work with time of day?

前端 未结 3 1490
梦如初夏
梦如初夏 2021-01-20 13:23

I am working with a schedule that specifies times of day, such as 10:30 AM. I do not know the dates, however. I\'m going to store these as values in a NSDictionary

3条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-20 14:17

    The short answer is that there's no built-in mechanism for storing time-of-day, so just use whatever is most convenient to you. I've used strings in the past using my own encoding and parsing code, (e.g., "22:00") because they're easy to read and debug, but there's nothing wrong with storing seconds or minutes past midnight as you suggest. Just remember that you'll have to do the math yourself.

    How ever you do it, you will need separate year, month, day, hour, minute, and second values so that you can construct an NSDate from NSDateComponents, using NSCalendar's -dateFromComponents: method.

    And as others have said, you cannot set the time-of-day by adding hours and minutes to an existing NSDate because if you cross a DST boundary you won't get the value you expect. (However, I assume you can still add day and month components without worrying about DST)

提交回复
热议问题