0

所以我使用这种方法将字符串转换为 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 上。

4

0 回答 0