开发者

WCF DateTime to NSDate

开发者 https://www.devze.com 2023-04-07 14:41 出处:网络
I am using a web services which returns a JSON WCF DateTime. The string goes like \\/Date(1316397792913+0800)\\/

I am using a web services which returns a JSON WCF DateTime.

The string goes like \/Date(1316397792913+0800)\/

I am interested in extracting out the 1316397792 which is the time since 1st Jan 1970 in seconds. So that I can use the NSDate timeIntervalSince1970 method to get the present time. I cropped out the last 3 digits as it's in milliseconds and the timeIntervalSince1970 takes in seconds.

Here's what I am currently doing which does not work for dates somewhere before 2001 which has a time interval in ms since 1970 less than 10 characters.

NSString *dateString = @"\/Date(1316397792913+0800)\/";
    NSLog(@"dateString :%@", dateString);

    NSDate *date = [NSDate dateWithTimeIntervalSince1970:
                    [[dateString substringWithRange:NSMakeRange(6, 10)] intValue]];
    NSLog(@"NSDate:%@", date);

dateString :/Date(1316397792913+0开发者_StackOverflow800)/
NSDate:2011-09-19 02:03:12 +0000

Therefore, I need a better work around playing with the dateString which does not assume everytime we will be feteching 10 characters.


You can simply get the substring between the index of ( and the index of +. Something like:

NSRange begin = [dateString rangeOfString:"("];
NSRange end = [dateString rangeOfString:"+"];
NSString* milliSecondsSince1970 = [dateString substringWithRange:NSMakeRange(begin.location + 1, end.location - begin.location - 1)];

P.S: Check for the one off error.

0

精彩评论

暂无评论...
验证码 换一张
取 消