Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize a NSDate object with a specific time

Tags:

iphone

nsdate

I have time in string format for example 2:00. I want to initialize it to NSDate with present date. I tried doing

   NSDateComponents *comps = [[NSDateComponents alloc] init];
   [comps setHour:2];

I am not able to compare this with a date object. Please help

like image 837
agupta Avatar asked Jan 25 '11 19:01

agupta


1 Answers

Try

NSDateComponents *comps = [[NSDateComponents alloc] init];
[comps setDay:6];
[comps setMonth:5];
[comps setYear:2004];

NSCalendar *gregorian = [[NSCalendar alloc]
    initWithCalendarIdentifier:NSGregorianCalendar];
NSDate *date = [gregorian dateFromComponents:comps];

You should be able to compare with date after that.

Maybe you mean something like. I think will set using today's date and then you can create NSDateComponents from that and set time values.

NSDate *today = [NSDate date];
NSCalendar *gregorian = [[NSCalendar alloc]
                         initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *weekdayComponents =
                    [gregorian components:(NSDayCalendarUnit | NSWeekdayCalendarUnit) fromDate:today];
[weekdayComponents setHour:12];
[weekdayComponents setMinute:10];
[weekdayComponents setSecond:30];
like image 167
menapole Avatar answered Sep 20 '22 16:09

menapole