How to parse a UTC epoch 1352716800 to NSDate?

孤者浪人 提交于 2019-12-12 04:46:11

问题


I'm reading data from a XML file which has a UTC date looking like "2011-05-04T00:00:00", and a UTC epoch looking like 1352716800.

Parsing the UTC epoch to NSDate would probably be much safer than messing around with a complex date format. How would I parse the UTC epoch to NSDate? With NSDateFormatter and a special format for "UTC Epoch"?

I think that it is [[NSDate alloc] initWithTimeIntervalSince1970:epoch] and a test seemed to work. But I am not sure if that's just correct by accident or if the "UTC epoch" is "Since 1970". The Apple Docs don't mention UTC Epoch.


回答1:


YES, you are correct it is UTC Epoch. For Reference if "Epoch time is UTC" checkout this

NSString *epochTime = @"1352716800";

// (Step 1) Convert epoch time to SECONDS since 1970
NSTimeInterval seconds = [epochTime doubleValue];
NSLog (@"Epoch time %@ equates to %qi seconds since 1970", epochTime, (long long) seconds);

// (Step 2) Create NSDate object
NSDate *epochNSDate = [[NSDate alloc] initWithTimeIntervalSince1970:seconds];
NSLog (@"Epoch time %@ equates to UTC %@", epochTime, epochNSDate);



回答2:


You don't really need to parse the UTC epoch date. Instead you can more or less directly create an NSDate instance from it:

long utcEpoch = 1352716800;
NSDate* date = [Date dateWithTimeIntervalSince1970: utcEpoch];



回答3:


In the case of the timestamp retrieved from Firebase (kFirebaseServerValueTimestamp), the epoch is expressed in milliseconds:

A placeholder value for auto-populating the current timestamp (time since the Unix epoch, in milliseconds) by the Firebase servers.

In that case dividing by 1000 is needed if you use initWithTimeIntervalSince1970 in iOS.



来源:https://stackoverflow.com/questions/12261196/how-to-parse-a-utc-epoch-1352716800-to-nsdate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!