我遇到了这个奇怪的问题,我的代码中的一个方法是在不同的ios版本中为相同的时间戳值返回不同的日期。
以下是该方法的代码。
+(NSDate *)getDateFromTheTimeStampAsDate:(NSInteger)timeStamp
{
NSLog(@"Timestamp - %d",timeStamp);
NSDateFormatter *dateFormatter=[[NSDateFormatter alloc] init];
NSLocale *usLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
[dateFormatter setLocale:usLocale];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"PST"]];
[dateFormatter setDateFormat:@"MMM DD,yyyy"];
return [dateFormatter dateFromString:[dateFormatter stringFromDate:[NSDate dateWithTimeIntervalSince1970:timeStamp]]];
}
对于timestamp = 1361581013,以下是从上面的函数返回的NSDates值:
iOS6 - 2013/02/01 iOS7 - 2013/02/22
这段代码有什么问题吗?
更新:我之前忘记查看日期格式。感谢其中一条评论我设法得到了正确的日期。这是遗留代码的一部分,因此决定将其删除并使用以下内容:
[NSDate dateWithTimeIntervalSince1970:timeStamp];
答案 0 :(得分:0)
首先输出不会接近日期。在终端上尝试日期-r 1361581013.至少你可以看到你是否越来越近了。
其次,将时间戳转换为NSDate。记录它是否关闭。
NSDate *d = [NSDate dateWithTimeIntervalSince1970:1361581013] ;
NSLog(@"d = %@" , d) ;
第三,在您知道获得NSDate之后,然后应用格式。
NSDateFormatter *df = [[NSDateFormatter alloc] init];
df.dateStyle = NSDateFormatterLongStyle;
df.timeStyle = NSDateFormatterLongStyle;
df.timeZone = [NSTimeZone timeZoneWithAbbreviation:@"PST" ];
NSLog(@"d with formatting 1 = %@" , [df stringFromDate:d]) ;
df.timeZone = [NSTimeZone timeZoneWithAbbreviation:@"EST" ];
NSLog(@"d with formatting 1 = %@" , [df stringFromDate:d]) ;
df.timeZone = [NSTimeZone timeZoneWithAbbreviation:@"GMT" ];
NSLog(@"d with formatting 1 = %@" , [df stringFromDate:d]) ;
然后你会知道你做对了。
d = 2013-02-23 00:56:53 +0000
d with formatting 1 = February 22, 2013 at 4:56:53 PM PST
d with formatting 1 = February 22, 2013 at 7:56:53 PM EST
d with formatting 1 = February 23, 2013 at 12:56:53 AM GMT