Creating NSDate from NSDateComponents off by one day

前端 未结 2 780
孤独总比滥情好
孤独总比滥情好 2021-01-25 14:32

I\'m trying to set a particular date for a unit test:

NSCalendar *calendar = [[NSCalendar alloc]
                         initWithCalendarIdentifier:NSGregorianC         


        
2条回答
  •  抹茶落季
    2021-01-25 14:46

    Try

    NSCalendar *calendar = [[NSCalendar alloc]
                             initWithCalendarIdentifier:NSGregorianCalendar];
    NSDateComponents *components = [[[NSDateComponents alloc] init] autorelease];
    [components setCalendar:calendar];
    [components setYear:2011];
    [components setMonth:5];
    [components setDay:12];
    [components setHour:1];
    [components setMinute:0];
    [components setSecond:0];
    [components setTimeZone:[NSTimeZone defaultTimeZone]];
    NSDate *date = [calendar dateFromComponents:components];
    

    or maybe you want

     [components setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]];
    

提交回复
热议问题