NSDateComponents回归奇怪的时刻

时间:2010-01-25 02:36:39

标签: iphone objective-c

我正在编写一些代码来获取服务器上的图像。图像文件名采用yyyyMMdd_HHmm格式(UTC格式),每3小时生成一次(1200,1500,1800,...等)。当代码开始时,我得到当前的UTC日期并提取时间。然后我从中创建一个NSDateComponent,并查看当前时间,将NSDateComponent的小时设置为下一个图像的小时。非常奇怪的是,如果我将小时设置为3,我从 NSCalendar dateFromComponents 返回的NSDate有一个不同的小时 ...给出了什么? (我已经在控制台输出中添加了。)

// get current time in UTC
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
NSTimeZone *UTC = [NSTimeZone timeZoneWithName:@"UTC"];
[dateFormatter setTimeZone:UTC];

//  get the current hour & min
[dateFormatter setDateFormat:@"HHmm"];
NSDate *today = [NSDate date];
NSString *str = [dateFormatter stringFromDate:today];
NSInteger hour = [str integerValue];
NSLog(str);

// find next image hour
NSCalendar *cal = [[NSCalendar alloc]   initWithCalendarIdentifier:NSGregorianCalendar];
unsigned unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit;
NSDateComponents *currentImageDateComps = [cal components:unitFlags fromDate:today];

if (hour > 2100) {
    [currentImageDateComps setHour:0];
    // add an extra day as next image is start of new day
    [currentImageDateComps setDay:[currentImageDateComps day]+1];

} else if (hour < 300) {
    [currentImageDateComps setHour:3];
} else if (hour < 600) {
    [currentImageDateComps setHour:6];
} else if (hour < 900) {
    [currentImageDateComps setHour:9];
} else if (hour < 1200) {
    [currentImageDateComps setHour:12];
} else if (hour < 1500) {
    [currentImageDateComps setHour:15];
} else if (hour < 1800) {
    [currentImageDateComps setHour:18];
} else if (hour < 2100) {
    [currentImageDateComps setHour:21];
}
[currentImageDateComps setMinute:0];


NSLog(@"hour %d", [currentImageDateComps hour]);
NSLog(@"minute %d", [currentImageDateComps minute]);
// construct the date
NSDate *currentImageDate = [cal dateFromComponents:currentImageDateComps];
[dateFormatter setDateFormat:@"yyyyMMdd_hhmm"];
NSString *nextImage = [dateFormatter stringFromDate:currentImageDate];

self.currentFilename = [nextImage stringByAppendingString:@".png"];
NSLog(self.currentFilename);

NSLogs生成的控制台输出是这样的。我得到的值为3小时,但它返回为'1700'?

2010-01-25 12:25:02.049预测[8447:207] viewDidLoad

2010-01-25 12:25:02.052预测[8447:207] 0225

2010-01-25 12:25:02.052预测[8447:207]小时3

2010-01-25 12:25:02.053预测[8447:207]分钟0

2010-01-25 12:25:02.053预测[8447:207] 20100124_1700.png

(我知道有一些内存释放问题,但我想先让它发挥作用..)

2 个答案:

答案 0 :(得分:6)

可能是时区问题?

答案 1 :(得分:1)

出了什么问题:

NSString *nextImage = [NSString stringWithFormat:@"%04d%02d%02d_%02d%02d.png", [currentImageDateComps year], [currentImageDateComps month], [currentImageDateComps day], [currentImageDateComps hour], [currentImageDateComps minute]];

self.currentFilename = nextImage;