Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WCF DateTime to NSDate

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+0800)/
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.

like image 711
Gavin Avatar asked Jul 04 '26 04:07

Gavin


1 Answers

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.

like image 87
Akshay Avatar answered Jul 05 '26 20:07

Akshay



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!