Skip to content

Instantly share code, notes, and snippets.

@tristandl
Forked from exalted/gist:726910
Created February 21, 2011 10:47
Show Gist options
  • Save tristandl/836914 to your computer and use it in GitHub Desktop.
Save tristandl/836914 to your computer and use it in GitHub Desktop.
/*
* This will convert DateTime (.NET) object serialized as JSON by WCF to a NSDate object.
*/
// Input string is something like: "/Date(1292851800000+0100)/", "\/Date(1292851800000-0100)\/" or "/Date(1292851800000)/" where
// 1292851800000 is milliseconds since 1970 and +0100 is the timezone
NSString *inputString = [item objectForKey:@"DateTimeSession"];
// This will tell number of seconds to add according to your default timezone
// Note: if you don't care about timezone changes, just delete/comment it out
NSInteger offset = [[NSTimeZone defaultTimeZone] secondsFromGMT];
// The start of the date value (can't assume position, because the / might be escaped)
NSInteger startPosition = [strValue rangeOfString:@"("].location + 1;
NSTimeInterval unixTime = [[strValue substringWithRange:NSMakeRange(startPosition, 13)] doubleValue] / 1000;
NSDate *date = [[NSDate dateWithTimeIntervalSince1970:unixTime]
dateByAddingTimeInterval:offset];
// You can just stop here if all you care is a NSDate object from inputString,
// or see below on how to get a nice string representation from that date:
// static is nice if you will use same formatter again and again (for example in table cells)
static NSDateFormatter *dateFormatter = nil;
if (dateFormatter == nil) {
dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateStyle:NSDateFormatterShortStyle];
[dateFormatter setTimeStyle:NSDateFormatterNoStyle];
// If you're okay with the default NSDateFormatterShortStyle then comment out two lines below
// or if you want four digit year, then this will do it:
NSString *fourDigitYearFormat = [[dateFormatter dateFormat]
stringByReplacingOccurrencesOfString:@"yy"
withString:@"yyyy"];
[dateFormatter setDateFormat:fourDigitYearFormat];
}
// There you have it:
NSString *outputString = [dateFormatter stringFromDate:date];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment