PPOTTime.m 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. //
  2. // PPOTTime.m
  3. // Copyright © 2015 PayPal, Inc. All rights reserved.
  4. //
  5. #import "PPOTMacros.h"
  6. #import "PPOTTime.h"
  7. @implementation PPOTTime
  8. + (NSDateFormatter *)rfc3339DateFormatter {
  9. /*
  10. Adapted from the Apple docs someplace...
  11. Note that this does not handle all possible
  12. RFC 3339 date time strings, just one of the most common styles.
  13. */
  14. static NSDateFormatter *rfc3339DateFormatter;
  15. static dispatch_once_t onceToken;
  16. dispatch_once(&onceToken, ^{
  17. rfc3339DateFormatter = [[NSDateFormatter alloc] init];
  18. NSLocale *enUSPOSIXLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
  19. [rfc3339DateFormatter setLocale:enUSPOSIXLocale];
  20. [rfc3339DateFormatter setDateFormat:@"yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'"];
  21. [rfc3339DateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
  22. });
  23. return rfc3339DateFormatter;
  24. }
  25. + (NSDateFormatter *)rfc3339MillisecondDateFormatter {
  26. static NSDateFormatter* rfc3339millisecondDateFormatter;
  27. static dispatch_once_t onceToken;
  28. dispatch_once(&onceToken, ^{
  29. rfc3339millisecondDateFormatter = [[PPOTTime rfc3339DateFormatter] copy];
  30. [rfc3339millisecondDateFormatter setDateFormat:@"yyyy'-'MM'-'dd'T'HH':'mm':'ss.SSS'Z'"];
  31. });
  32. return rfc3339millisecondDateFormatter;
  33. }
  34. // sometimes the server supplied date has a millisecond component. Sometimes not. Easier to just deal with it.
  35. + (NSDate *)dateFromRFC3339LikeString:(NSString *)dateStr {
  36. if (dateStr == nil) {
  37. return nil;
  38. }
  39. NSDate* result = [[PPOTTime rfc3339DateFormatter] dateFromString:dateStr];
  40. if (!result) {
  41. result = [[PPOTTime rfc3339MillisecondDateFormatter] dateFromString:dateStr];
  42. if (!result) {
  43. PPLog(@"WARNING - could not parse '%@' into date!", dateStr);
  44. }
  45. }
  46. return result;
  47. }
  48. @end