【问题标题】:About JSON Date Conversion error关于 JSON 日期转换错误
【发布时间】:2013-03-29 03:11:44
【问题描述】:

我得到 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)

【问题讨论】:

标签: iphone ios nsdate nsdateformatter


【解决方案1】:

参考我的回答:

iPhone:How to convert Regular Expression into Date Format?

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

- (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];

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-09-19
    • 1970-01-01
    • 1970-01-01
    • 2013-07-31
    • 1970-01-01
    • 2022-01-19
    • 1970-01-01
    相关资源
    最近更新 更多