8

I am working with an API that returns a .NET DateTime object into my iOS application. I'm a little confused at what's going on, the DateTime looks fine when it leaves the API, but when it comes in it goes through JSON and comes in as a string that looks like this:

/Date(1303884000000-0600)/

WTF is that and how can I turn it into a NSDate object??

Thanks!

Buchannon
  • 1,671
  • 16
  • 28

3 Answers3

12

From Parsing JSON dates on IPhone I found the following function to be perfect:

    - (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];
}
Community
  • 1
  • 1
Buchannon
  • 1,671
  • 16
  • 28
4

The RestKit library has an NSDateFormatter subclass for just this. Take a look here for inspiration:

https://github.com/RestKit/RestKit/blob/master/Code/Support/RKDotNetDateFormatter.h https://github.com/RestKit/RestKit/blob/master/Code/Support/RKDotNetDateFormatter.m

Justyn
  • 1,442
  • 12
  • 27
2

Essentially what you're getting there is milliseconds from January 1st 1970 UTC, with the -0600 being the timezone offset. Take a look at this blog post http://weblogs.asp.net/bleroy/archive/2008/01/18/dates-and-json.aspx

You would probably have to write a custom NSDateFormatter to handle a date in that format, or you could format it in .NET (easier), output a string in JSON, and then use a standard NSDateFormatter.

psy
  • 2,791
  • 26
  • 26
  • I can't figure out why there are 3 extra zeros at the end of the string though. Using unix time converter with "1303884000000" I get the wrong date. If I get rid of the 3 zeros and convert with "1303884000" I get the right date. What are those extra zeros for (or from)?? – Buchannon Apr 27 '11 at 21:00
  • Oh, I guess it's milliseconds since 1970 instead of just seconds. So to parse this as a NSDate, I'd have to strip out all the characters and then compare time since 1970?? – Buchannon Apr 27 '11 at 21:07
  • You can do it that way. You could then add/subtract hours to adjust timezone if necessary. Like i said previously, you may want to do some more formatting on the .NET side as it's probably easier that way :) – psy Apr 27 '11 at 21:13
  • Ahh problem solved and a function to parse! http://stackoverflow.com/questions/1757303/parsing-json-dates-on-iphone – Buchannon Apr 27 '11 at 22:06