Guest User

Untitled

a guest
Jul 23rd, 2018
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.95 KB | None | 0 0
  1. /*
  2. * This will convert DateTime (.NET) object serialized as JSON by WCF to a NSDate object.
  3. */
  4.  
  5. // Input string is something like: "/Date(1292851800000+0100)/", "\/Date(1292851800000-0100)\/" or "/Date(1292851800000)/" where
  6. // 1292851800000 is milliseconds since 1970 and +0100 is the timezone
  7. NSString *inputString = [item objectForKey:@"DateTimeSession"];
  8.  
  9. // This will tell number of seconds to add according to your default timezone
  10. // Note: if you don't care about timezone changes, just delete/comment it out
  11. NSInteger offset = [[NSTimeZone defaultTimeZone] secondsFromGMT];
  12.  
  13. // The start of the date value (can't assume position, because the / might be escaped)
  14. NSInteger startPosition = [strValue rangeOfString:@"("].location + 1;
  15.  
  16. NSTimeInterval unixTime = [[strValue substringWithRange:NSMakeRange(startPosition, 13)] doubleValue] / 1000;
  17.  
  18. NSDate *date = [[NSDate dateWithTimeIntervalSince1970:unixTime]
  19. dateByAddingTimeInterval:offset];
  20. // You can just stop here if all you care is a NSDate object from inputString,
  21. // or see below on how to get a nice string representation from that date:
  22.  
  23. // static is nice if you will use same formatter again and again (for example in table cells)
  24. static NSDateFormatter *dateFormatter = nil;
  25. if (dateFormatter == nil) {
  26. dateFormatter = [[NSDateFormatter alloc] init];
  27. [dateFormatter setDateStyle:NSDateFormatterShortStyle];
  28. [dateFormatter setTimeStyle:NSDateFormatterNoStyle];
  29.  
  30. // If you're okay with the default NSDateFormatterShortStyle then comment out two lines below
  31. // or if you want four digit year, then this will do it:
  32. NSString *fourDigitYearFormat = [[dateFormatter dateFormat]
  33. stringByReplacingOccurrencesOfString:@"yy"
  34. withString:@"yyyy"];
  35. [dateFormatter setDateFormat:fourDigitYearFormat];
  36. }
  37.  
  38. // There you have it:
  39. NSString *outputString = [dateFormatter stringFromDate:date];
Add Comment
Please, Sign In to add comment