如何将长整数时间转换为NSString或NSDate来显示时间?

Lot*_*rio 8 nsdate ios long-integer

我从Java Date获得了一个序列号,它转换成长整数,如"1352101337000".我遇到的问题是如何将这个长整数分析回NSDate或NSString,以便我可以清楚知道序列号显示的时间.

有没有人能解决这个案子?

iDe*_*Dev 8

用这个,

NSTimeInterval timeInMiliseconds = [[NSDate date] timeIntervalSince1970];
Run Code Online (Sandbox Code Playgroud)

要改回来,

NSDate* date = [NSDate dateWithTimeIntervalSince1970:timeInMiliseconds];
Run Code Online (Sandbox Code Playgroud)

根据苹果文档,

NSTimeInterval:用于指定时间间隔,以秒为单位.

typedef double NSTimeInterval;

它是double类型.

要将日期转换为字符串,

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss zzz"];

//Optionally for time zone converstions
[formatter setTimeZone:[NSTimeZone timeZoneWithName:@"..."]];

NSString *stringFromDate = [formatter stringFromDate:myNSDateInstance];

[formatter release];
Run Code Online (Sandbox Code Playgroud)

  • 还要检查是否需要添加:[NSDate dateWithTimeIntervalSince1970:(ms/1000)]; (2认同)