我从Java Date得到了一个序列号,将其转换为长整型,例如“1352101337000”。
我遇到的问题是如何将这个长整数分析回NSDate或NSString,以便我清楚地知道序列号显示的时间。
有人有解决这个问题的方法吗?
NSTimeInterval timeInMiliseconds = [[NSDate date] timeIntervalSince1970];
NSDate* date = [NSDate dateWithTimeIntervalSince1970:timeInMiliseconds];
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 3,本解答已做更新,不再使用 NSDate
。
按照以下步骤将长整型转换为日期字符串。
// 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
[NSDate dateWithTimeIntervalSince1970:(ms / 1000)];
- Pach