Initialize a NSDate object with a specific time

后端 未结 5 1884
一整个雨季
一整个雨季 2021-02-14 11:17

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

5条回答
  •  迷失自我
    2021-02-14 11:33

    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];
    

提交回复
热议问题