Formatting a DateTime from .NET to NSDate for objective-c

I am working with an API that returns a .NET DateTime object in my iOS application. I got a little confused about what happens, DateTime looks great when it exits the API, but when it comes in, it goes through JSON and enters a line that looks like this:

/Date(1303884000000-0600)/ 

WTF is this and how can I turn it into an NSDate object?

Thanks!

+6
source share
3 answers

From Parsing JSON Dates on IPhone I found that the following function is perfect:

  - (NSDate*) getDateFromJSON:(NSString *)dateString { // Expect date in this format "/Date(1268123281843)/" int startPos = [dateString rangeOfString:@"("].location+1; int endPos = [dateString rangeOfString:@")"].location; NSRange range = NSMakeRange(startPos,endPos-startPos); unsigned long long milliseconds = [[dateString substringWithRange:range] longLongValue]; NSLog(@"%llu",milliseconds); NSTimeInterval interval = milliseconds/1000; return [NSDate dateWithTimeIntervalSince1970:interval]; } 
+11
source
+4
source

Essentially, you get milliseconds from January 1, 1970 UTC, and -0600 is the clockwise offset. Take a look at this blog post http://weblogs.asp.net/bleroy/archive/2008/01/18/dates-and-json.aspx

You may have to write your own NSDateFormatter to handle the date in this format, or you can format it in .NET (easier), output the string in JSON, and then use the standard NSDateFormatter.

+2
source

Source: https://habr.com/ru/post/886826/


All Articles