Created
December 3, 2010 12:42
-
-
Save exalted/726910 to your computer and use it in GitHub Desktop.
This will convert DateTime (.NET) object serialized as JSON by WCF to a NSDate object
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* This will convert DateTime (.NET) object serialized as JSON by WCF to a NSDate object. | |
*/ | |
// Input string is something like: "/Date(1292851800000+0100)/" 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]; | |
// A range of NSMakeRange(6, 10) will generate "1292851800" from "/Date(1292851800000+0100)/" | |
// as in example above. We crop additional three zeros, because "dateWithTimeIntervalSince1970:" | |
// wants seconds, not milliseconds; since 1 second is equal to 1000 milliseconds, this will work. | |
// Note: if you don't care about timezone changes, just chop out "dateByAddingTimeInterval:offset" part | |
NSDate *date = [[NSDate dateWithTimeIntervalSince1970: | |
[[inputString substringWithRange:NSMakeRange(6, 10)] intValue]] | |
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
Check out also RestKit/RestKit#264