简体   繁体   English

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

[英]How to convert long-integer time to NSString or NSDate to display time?

I got a serial number form Java Date which convert into long-integer such as "1352101337000". 我从Java Date获得了一个序列号,它转换成长整数,如“1352101337000”。 The problem I met is how to analyze this long-integer number back to NSDate or NSString so that I can clear to know what time the serial number is displaying. 我遇到的问题是如何将这个长整数分析回NSDate或NSString,以便我可以清楚知道序列号显示的时间。

Do anybody have solution for this case? 有没有人能解决这个案子?

Use this, 用这个,

NSTimeInterval timeInMiliseconds = [[NSDate date] timeIntervalSince1970];

To change it back, 要改回来,

NSDate* date = [NSDate dateWithTimeIntervalSince1970:timeInMiliseconds];

As per apple documentation , 根据苹果文档

NSTimeInterval: Used to specify a time interval, in seconds. NSTimeInterval:用于指定时间间隔,以秒为单位。

typedef double NSTimeInterval; typedef double NSTimeInterval;

It is of type double. 它是double类型。

To convert a date to string, 要将日期转换为字符串,

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];

Swift 迅速

This answer has been updated for Swift 3, and thus no longer uses NSDate . 此答案已针对Swift 3进行了更新,因此不再使用NSDate

Do the following steps to convert a long integer to a date string. 执行以下步骤将长整数转换为日期字符串。

// convert to seconds
let timeInMilliseconds = 1352101337001
let timeInSeconds = Double(timeInMilliseconds) / 1000

// get the Date
let dateTime = Date(timeIntervalSince1970: timeInSeconds)

// display the date and time
let formatter = DateFormatter()
formatter.timeStyle = .medium
formatter.dateStyle = .long
print(formatter.string(from: dateTime)) // November 5, 2012 at 3:42:17 PM

Notes 笔记

  • Since Java dates are stored as long integers in milliseconds since 1970 this works. 由于Java日期自1970年以来以毫秒为单位存储为long整数,因此可行。 However, make sure this assumption is true before just converting any old integer to a date using the method above. 但是,在使用上述方法将任何旧整数转换为日期之前,请确保此假设为真。 If you are converting a time interval in seconds then don't divide by 1000, of course. 如果您要以秒为单位转换时间间隔,那么当然不要除以1000。
  • There are other ways to do the conversion and display the string. 还有其他方法可以进行转换并显示字符串。 See this fuller explanation . 看到这个更全面的解释

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

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