NSDate from stange looking string

南笙酒味 提交于 2019-12-02 14:18:28

问题


I have an NSDictionary with the value for date as: "Date":"/Date(1314313200000+0100)/",
How can I turn this into an NSDate as it contains strings lie "Date": and / ?


回答1:


1314313200000 is milliseconds since the epoch-date (1970-01-01), and 0100 is the timezone. You need to parse this info out from the string and build a date from it. The NSScanner class is a good fit for parsing information out of strangely formatted text.

// Init a scanner with your date string
NSScanner* scanner = [NSScanner scannerWithString:@"Date:/Date(1314313200000+0100)/"];
// Skip everything up to a valid numeric character
[scanner scanUpToCharactersFromSet:[NSCharacterSet decimalDigitCharacterSet]
                        intoString:NULL];
// Parse numeric value into a 64bit variable
long long milliseconds = 0;
[scanner scanLongLong:&milliseconds];
// Create a date instance from milliseonds sinve 1970-01-01
NSDate* date = [NSDate dateWithTimeIntervalSince1970:milliseconds / 1000.0];

If the time-zone is also important just skip the + sign and parse a new number.



来源:https://stackoverflow.com/questions/7038117/nsdate-from-stange-looking-string

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