NSDate from stange looking string

前端 未结 1 1194
面向向阳花
面向向阳花 2021-01-28 17:18

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条回答
  • 2021-01-28 17:27

    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.

    0 讨论(0)
提交回复
热议问题