开发者

Easiest way to get an NSDate representation of "the next 7am that will occur" in Cocoa?

开发者 https://www.devze.com 2023-01-01 08:48 出处:网络
I figure I can achieve what I want by using NSCalendar and NSDateComponents, but that would run something like the following:

I figure I can achieve what I want by using NSCalendar and NSDateComponents, but that would run something like the following:

  • Get "now"
  • Create an NSDateComponents from "now".
  • If "now" is pre-7am, then use today's date.
  • If "now" is post-7am, use tomorrow's date.
    • If today is the last day of the month, increase month, set day to 1.
      • If it was December, increase year by 1 also.
  • Set hour, minute, second.
  • Create a new NSDate.

It all seems very long-winded, but that appears to be what other answers on here suggest, and the documentation doesn't offer any clues. I'm 开发者_运维知识库going back and forth between all the date and calendar classes I can find.

Is there a simple way to ask for the "next occurring 7am"?


I haven't tried it, but I think this would work:

  • Get Now date.
  • Create NSDateComponents from Now.
  • Set hour component to 7.
  • Convert 7am date components back to an NSDate.
  • If the 7am date is later than Now, you're done.
  • Otherwise, use -[NSCalendar dateByAddingComponents:options:] to advance the 7am date by one day.

I'm not sure if that last step would do the right thing if a daylight savings change happened between one 7am and the next.

0

精彩评论

暂无评论...
验证码 换一张
取 消