我在 mysql 中有一个表,记录线程被存储时的时间戳,但我似乎无法在应用程序上显示正确的时间。
日期 ([dict objectForKey:@"AT_Date"]
) 返回 2015-06-15 15:12:04,但我不知道这是否正确,如我所想它应该返回一个长数字。而我转换回本地日期时的最终日期总是输出 1970-01-01 00:33:35 +0000,这是错误的。为什么会这样?
代码:
if((NSNull *)[dict objectForKey:@"AT_Date"] != [NSNull null]){
NSString *timestampString = [dict objectForKey:@"AT_Date"];
double timestampDate = [timestampString doubleValue];
at_Date = [NSDate dateWithTimeIntervalSince1970:timestampDate];
if (counter == 1) {
lastDateForumActivity = timestampString;
}
}
最佳答案
错误:
当您从 timestampString
中获取 doubleValue
时,它应该获取可以转换为 double
的字符串部分,这只会是 2015 年。然后您在 01-01-1970 00:00:00
之后创建一个 2015 秒的 NSDate
。一小时是 3600 秒,半小时是 1800 秒,所以午夜后大约 33 分钟的时间看起来是合理的。
怎么做:
创建一个 NSDateFormatter
并对其进行设置,使其与您从查询中获得的内容相匹配。例如:
NSString *timestampString = @"2015-06-15 15:12:04"; // [dict objectForKey:@"AT_Date"];
NSDateFormatter *df = [[NSDateFormatter alloc] init];
NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
[df setLocale:locale];
NSTimeZone *tz = [NSTimeZone timeZoneWithName:@"UTC"];
[df setTimeZone:tz];
[df setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSDate *timestampDate = [df dateFromString:timestampString];
NSLog(@"date = %@", timestampDate);
// outputs: "... date = 2015-06-15 15:12:04 +0000"
关于ios - 从 NSString 时间戳返回正确的 NSDate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30849473/