0

我得到 JSON Parse Date,我想使用 NSDateFormatter,但没有成功。

1.JSON 获取控制台日志

IncidentReceiveTime = "/Date(1353914100000+0800)/";

2.我的代码

NSString *dateStr =[NSString stringWithFormat:@"%@",[[[DateSortArry objectAtIndex:0] objectForKey:@"IncidentReceiveTime"]stringByReplacingOccurrencesOfString:@"/" withString:@""]];
    NSLog(@"dateStr:%@",dateStr);

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    [dateFormatter setLocale:[NSLocale currentLocale]];
    [dateFormatter setDateFormat:@"yyyy-MM-ddHH"];
    NSDate *date = [dateFormatter dateFromString:dateStr];
    NSLog(@"date:%@",date);

3.NSDateFormatter控制台日志

dateStr:Date(1361943694000+0800)
date:(null)
4

1 回答 1

2

参考我的回答:

iPhone:如何将正则表达式转换为日期格式?

在这里,我在上面的链接中从我的答案中发布了这段代码,好像以防万一将来上面的链接失效,那么这个答案就不会变得无用:

- (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;
    return [NSDate dateWithTimeIntervalSince1970:interval];
}

从上述方法获得 NSDate 对象后:

NSDateFormatter *dateForm = [[NSDateFormatter alloc] init];
[dateForm setDateFormat:@"yyyy-MM-dd hh:mm:ss"];
NSString *dateStr = [dateForm stringFromDate:<YourNSDateObject>];
[dateForm setDateFormat:@"<Your Desired Date Format>"];
NSDate *desireddate = [dateForm dateFromString:dateStr];

希望这可以帮助。

于 2013-07-25T07:25:17.883 回答