Created
April 16, 2014 08:46
-
-
Save sag333ar/10834909 to your computer and use it in GitHub Desktop.
Convert UnixTimeStamp Date with specified Timezone. Example "/Date(1395486890000+0530)/" as a sample value.
This file contains 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
// Convert UnixTimeStamp Date with specified Timezone. Example "/Date(1395486890000+0530)/" as a sample value. | |
+ (NSDate *)DateFromJSONString:(NSString *)string { | |
static NSRegularExpression *dateRegEx = nil; | |
static dispatch_once_t onceToken; | |
dispatch_once(&onceToken, ^{ | |
dateRegEx = [[NSRegularExpression alloc] initWithPattern:@"^\\/date\\((-?\\d++)(?:([+-])(\\d{2})(\\d{2}))?\\)\\/$" options:NSRegularExpressionCaseInsensitive error:nil]; | |
}); | |
NSTextCheckingResult *regexResult = [dateRegEx firstMatchInString:string options:0 range:NSMakeRange(0, [string length])]; | |
if (regexResult) { | |
// milliseconds | |
NSTimeInterval seconds = [[string substringWithRange:[regexResult rangeAtIndex:1]] doubleValue] / 1000.0; | |
// timezone offset | |
if ([regexResult rangeAtIndex:2].location != NSNotFound) { | |
NSString *sign = [string substringWithRange:[regexResult rangeAtIndex:2]]; | |
// hours | |
seconds += [[NSString stringWithFormat:@"%@%@", sign, [string substringWithRange:[regexResult rangeAtIndex:3]]] doubleValue] * 60.0 * 60.0; | |
// minutes | |
seconds += [[NSString stringWithFormat:@"%@%@", sign, [string substringWithRange:[regexResult rangeAtIndex:4]]] doubleValue] * 60.0; | |
} | |
return [NSDate dateWithTimeIntervalSince1970:seconds]; | |
} | |
return nil; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment