從 JSON 日期格式獲取 NSDate 日期(1268123281843)

在 Json.NET 4.5 之前,日期是使用 Microsoft 格式編寫的:“/ Date(1198908717056)/”。如果你的伺服器以此格式傳送日期,你可以使用以下程式碼將其序列化為 NSDate:

Objective-C

(NSDate*) getDateFromJSON:(NSString *)dateString
{
    // Expect date in this format "/Date(1268123281843)/"
    int startPos = [dateString rangeOfString:@"("].location+1;
    int endPos = [dateString rangeOfString:@")"].location;
    NSRange range = NSMakeRange(startPos,endPos-startPos);
    unsigned long long milliseconds = [[dateString substringWithRange:range] longLongValue];
    NSLog(@"%llu",milliseconds);
    NSTimeInterval interval = milliseconds/1000;
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:interval];
    // add code for date formatter if need NSDate in specific format.
    return date;
}