我正在尝试将字符串格式的日期转换为 NSDate,但是结果似乎从传入的时间中扣除了一个小时。有什么想法吗?
-(NSDate *) convertStringToDate:(NSString *)theString {
//init formatter
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
//setup the formatter
[dateFormat setDateFormat:@"dd-MM-yyyy HH:mm"];
[dateFormat setTimeZone:[NSTimeZone localTimeZone]];
//cast the date from the string
NSDate *date = [dateFormat dateFromString:theString];
[dateFormat release];
return date;
}
这是测试调用:
NSDate *testDate = [self convertStringToDate:@"28-03-2012 11:46"];
NSLog(@"converted test date - %@", testDate);
我得到输出(这是我指定为参数的时间之前的一个小时):
converted test date - 2012-03-28 10:46:00 +0000
任何有关如何更改时区的帮助将不胜感激。
最佳答案
当您 NSLog
一个 NSDate
时,它不会显示在您的本地时区中。它以 GMT 显示。您本地的时区目前比 GMT 早 1 小时(可能是因为夏令时)。
要将日期转换为相对于您本地时区的字符串,您需要使用日期格式化程序(默认情况下,日期格式化程序的时区将设置为您本地时区):
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = @"yyyy-MM-dd'T'HH:mm";
NSLog(@"converted test date - %@", [dateFormatter stringFromDate:testDate]);
关于objective-c - 将字符串转换为日期会损失一个小时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9906069/