How to Get an NSDate for a Specific Day of Week and Time from an Existing NSDate

Worst Post Title ever! This one took me a bit to figure out so I thought I’d post it in case anyone else out there had troubles. I wanted to get an NSDate for a specific day of the week and time from an existing NSDate object in order to create a countdown timer.

This example will get you the NSDate for the following Monday at 8am:

NSDate *today = [NSDate date];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
[gregorian setLocale:[NSLocale currentLocale]];

NSDateComponents *nowComponents = [gregorian components:NSYearCalendarUnit | NSWeekCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit fromDate:today];

[nowComponents setWeekday:2]; //Monday
[nowComponents setWeek: [nowComponents week] + 1]; //Next week
[nowComponents setHour:8]; //8a.m.
[nowComponents setMinute:0];
[nowComponents setSecond:0];

NSDate *beginningOfWeek = [gregorian dateFromComponents:nowComponents];

Now that you have the new NSDate, you can calculate the difference between the two by using fromDate.

7 responses to “How to Get an NSDate for a Specific Day of Week and Time from an Existing NSDate”

  1. Thanks Dan,
    I’ve been wondering how i can get a date for next monday (with Ann) and count down from today!?? I guess i have no idea what you are talking about but i’m sure in you tech world it means a lot to some.
    I guess i’m more of a picture of castles kind of a guy.

    See ya soon.


  2. Thanks very much for this. Of all things Objective-C, I find NSDate to be the most inscrutable! Have bookmarked this page for future reference. Many thanks.


    • I think setting the locale will take into account the start of their week. I’m not completely certain though as I only needed to use this for users in the U.K.


  3. Thanks, Work perfect with swift

    //Set Date and Hour at 00-00-00, 00:00
    var hourStart = NSDateComponents()
    var calendar = NSCalendar()
    calendario.locale = NSLocale.currentLocale() = 01
    hourStart.month = 01
    hourStart.year = 01
    hourStart.hour = 00
    hourStart.minute = 00
    var dateCustom = calendar.dateFromComponents(hourStart)

    Liked by 1 person

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: