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”
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.
LikeLike
I will upload castle pictures soon 🙂
LikeLike
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.
LikeLike
Thank you, this was very helpful. They key line i was missing is this:
[nowComponents setWeek: [nowComponents week] + 1]; //Next week
LikeLike
What if the users week is set to start on monday?
Does that not matter due to the “gregorian” calendar setting?
LikeLike
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.
LikeLike
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()
hourStart.day = 01
hourStart.month = 01
hourStart.year = 01
hourStart.hour = 00
hourStart.minute = 00
var dateCustom = calendar.dateFromComponents(hourStart)
LikeLiked by 1 person