0

I get JSON Parse Date, I want to use NSDateFormatter,but not success.

1.JSON Get console Log

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

2.my code

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 console log

dateStr:Date(1361943694000+0800)
date:(null)
Parth Bhatt
  • 19,381
  • 28
  • 133
  • 216
SimonKira
  • 91
  • 1
  • 4
  • 13
  • Try the `setDateStyle:` property for `NSDateFormatter` object. – Malloc Mar 29 '13 at 03:23
  • possible duplicate of [Parsing JSON dates on IPhone](http://stackoverflow.com/questions/1757303/parsing-json-dates-on-iphone) – rmaddy Mar 29 '13 at 03:58

1 Answers1

2

Refer to my answer in :

iPhone:How to convert Regular Expression into Date Format?

Here I am posting this code from my answer in the above link as if in case in future the above link goes down then this answer doesn't become useles:

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

Once you get NSDate object from above method:

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

Hope this helps.

Community
  • 1
  • 1
Parth Bhatt
  • 19,381
  • 28
  • 133
  • 216