简体   繁体   English

如何将unix时间戳转换为人类可读时间?

[英]How to convert unix timestamp to human readable time?

I get a unix timestamp from the database and I am trying to create a human readable date from it. 我从数据库中获取了一个unix时间戳,我正在尝试从中创建一个人类可读的日期。 I am using this way 我正在用这种方式

long t1=[time longLongValue];

NSDate* date=[NSDate dateWithTimeIntervalSince1970:t1];

where time is the timestamp. 其中时间是时间戳。 When I print date I get 当我打印日期时,我得到了

1956-02-18 19:04:01 +0000 

instead of 代替

2013-01-02 12:31:03 +0000

The timestamp was 1356765933449 时间戳是1356765933449

It is a matter of integer overflow, as Boris correctly pointed out in his answer. 这是一个整数溢出的问题,正如鲍里斯在他的回答中正确指出的那样。

I don't know what your time object is, but instead of a signed long int use a NSTimeInterval . 我不知道你的time对象是什么,但是使用NSTimeInterval代替signed long int

On iOS NSTimeInterval is currently defined as 在iOS上, NSTimeInterval目前定义为

typedef double NSTimeInterval;

but you shouldn't care too much about that. 但是你不应该太在意这件事。 Sticking with type synonyms will protect you in case Apple decides to change the underlying definition to something else. 如果Apple决定将基础定义更改为其他内容,那么坚持使用类型同义词将保护您。

That said you should change your code to something like 那说你应该改变你的代码

NSTimeInterval epoch = [time doubleValue];
NSDate * date = [NSDate dateWithTimeIntervalSince1970:epoch];

Concerning the code maintainability issue I described before, here you are explicitly using a doubleValue (you don't have many options), but the good thing is that if Apple changes the NSTimeInterval definition to something not compatible with a double assignment, the compiler will let you know. 关于我之前描述的代码可维护性问题,这里你明确使用了一个doubleValue (你没有很多选项),但好处是如果Apple将NSTimeInterval定义更改为与double赋值不兼容的东西,编译器将让你知道。

Try this 尝试这个

- (NSString *) getDateFromUnixFormat:(NSString *)unixFormat
{

    NSDate *date = [NSDate dateWithTimeIntervalSince1970:[unixFormat intValue]];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    [dateFormatter setDateFormat:@"MMM dd, yyyy-h:mm"];
    [dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
    //NSDate *date = [dateFormatter dateFromString:publicationDate];
    NSString *dte=[dateFormatter stringFromDate:date];

    [dateFormatter release];
    return dte;

}

The Unix timestamp has only 32 Bits available. Unix时间戳只有32位可用。

Because they use a signed int, they count the seconds from 1.1.1970. 因为它们使用signed int,所以它们计算从1.1.1970开始的秒数。 A 32 Bit signed int can only hold values up to 2147483647, where as you want it to be 1356765933449 . 32位signed int只能保存1356765933449 2147483647,您希望它在1356765933449 That causes an overflow, and that causes your date to be invalid. 这会导致溢出,导致您的日期无效。

This is also known as the Year 2038 Problem , because 2147483647 (max value) will be hit on 03:14:07 UTC on Tuesday, 19 January 2038. 这也被称为Year 2038 Problem ,因为2147483647(最大值)将于2038年1月19日星期二03:14:07 UTC发布。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM