NSDateComponents返回错误的日期(关闭10天)

时间:2013-06-05 17:52:21

标签: ios nsdate nsdatecomponents

所以我使用此方法将字符串转换为NSDate。几小时之前,它工作正常,但突然NSDateComponents返回错误的日期。我不知道为什么。

   - (NSDate *)NSDateFromDate: (NSString *) str
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"yyyy-MM-dd"];

    NSDate *date = [formatter dateFromString:str];

    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    // extracting components from date
    unsigned units = NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit | NSWeekdayCalendarUnit;
    NSDateComponents *components = [calendar components:units fromDate:date];

    int dayIndex = [components weekday]; // sunday = 1
    int dayDate = [components day];
    NSLog(@"%@ => %@ (date = %i, weekday = %i) " ,str,date, dayDate, dayIndex);


    return date;
}

这是日志

2013-06-05 => 2013-06-04 17:17:56 +0000 (date = 14, weekday = 3) 
2013-06-06 => 2013-06-05 17:17:56 +0000 (date = 15, weekday = 4) 
2013-06-07 => 2013-06-06 17:17:56 +0000 (date = 16, weekday = 5) 

NSDate显示它是6月4日,但component表示日期是14日。

更新 - 我在模拟器上尝试了代码并且工作正常,因此问题出在我的iPhone 4上。

0 个答案:

没有答案