NSDate from stange looking string

2020-05-06 11:50发布

问题:

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.