Skip to content

Instantly share code, notes, and snippets.

@weejayuk
Created August 5, 2011 10:19
Show Gist options
  • Save weejayuk/1127268 to your computer and use it in GitHub Desktop.
Save weejayuk/1127268 to your computer and use it in GitHub Desktop.
NSDate Extension to create .net JSON date strings and convert back. Testing for this was very limited, so use with caution. Some of the code was taken from here. http://www.pittle.org/weblog/how-to-convert-datetime-net-object-serialized-as-json-by-wcf-to-
NSDate *timenow=[NSDate date];
NSLog(@"Date before date2dot net=%@",[timenow description]);
NSString *date2DotNet=[timenow dateToDotNet];
NSLog(@"Dot net version of now = %@",date2DotNet);
timenow=[NSDate dateFromDotNet:date2DotNet];
NSLog(@"Date back from date2dot net=%@",[timenow description]);
#import <Foundation/Foundation.h>
@interface NSDate (DotNetDates)
+(NSDate*) dateFromDotNet:(NSString*)stringDate;
-(NSString*) dateToDotNet;
@end
#import "NSDate+DotNetDates.h"
@implementation NSDate (DotNetDates)
+(NSDate*) dateFromDotNet:(NSString*)stringDate{
NSDate *returnValue;
if ([stringDate isMemberOfClass:[NSNull class]]) {
returnValue=nil;
}
else {
NSInteger offset = [[NSTimeZone defaultTimeZone] secondsFromGMT];
returnValue= [[NSDate dateWithTimeIntervalSince1970:
[[stringDate substringWithRange:NSMakeRange(6, 10)] intValue]]
dateByAddingTimeInterval:offset];
}
return returnValue;
}
-(NSString*) dateToDotNet{
double timeSince1970=[self timeIntervalSince1970];
NSInteger offset = [[NSTimeZone defaultTimeZone] secondsFromGMT];
offset=offset/3600;
double nowMillis = 1000.0 * (timeSince1970);
NSString *dotNetDate=[NSString stringWithFormat:@"/Date(%.0f%+03d00)/",nowMillis,offset] ;
return dotNetDate;
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment