Search code examples
iosobjective-cnsdatensdateformatter

Create NSDate with a specific time


I have the following problem. I need to create an NSDate object from a specific time. The time is 6 pm for today in a given timezone (sometimes CST, EST etc). Not 6 pm for every day, but 6pm for today in that particular timezone.

I was thinking of using the NSCalendar object to create the specific date/time but the problem is that it needs a day, month and year. So how do I set these values when I don't have the correct date for it. Example :

Today is 28th January 2014, 11:09 in CST. Now if I need to create a NSCalendar object I would need the day, month and year. I cannot use the NSDate object's day, month and year calculations as it will lead to problems with edge cases.

Can anyone point me in the right direction?


Solution

  • Your concern seems to be about edge cases, this suggests to me that rather than "6pm today" you are actually looking for the "next 6pm", i.e. if the time is past 6pm you want 6pm tomorrow?

    Maybe the following will help, whether my guess is correct or not:

    1. Get the current date & time - NSDate
    2. Get the current calendar - NSCalendar
    3. Set the time zone of the calendar to your desired time zone
    4. Using the calendar convert the date to components - NSDateComponents - only extracting the components for year, month, day, hour & time zone. You now have the current time components in the target time zone rounded down to the nearest hour.
    5. Create an NSDate from your extracted time components using your calendar. You now have your rounded down time as an NSDate.
    6. Using your components calculate the number of hours to add to advance the time to the next 6pm.
    7. Convert the number of hours to seconds to produce an NSTimeInterval value, add that interval to your rounded down date. NSDate will take care of the edge cases of advancing the date, changing the month, etc. as needed.

    HTH