onmyway133 / notes

:notebook_with_decorative_cover: Issues and solutions I found during development, mostly iOS
https://onmyway133.com/
MIT License
63 stars 4 forks source link

IOS 8601 strings #121

Open onmyway133 opened 8 years ago

onmyway133 commented 8 years ago

2012-09-25T07:54:41-07:00 2011-01-26T19:06:43Z 2011-01-26 19:06:43 +0000

onmyway133 commented 8 years ago
public struct Formatter {

  private static let basicFormatter = NSDateFormatter().then {
    $0.locale = NSLocale(localeIdentifier: "en_US_POSIX")
    $0.dateFormat = "yyyy-MM-dd'T'HH:mm:ss'Z'"
    $0.timeZone = NSTimeZone(abbreviation: "UTC")
  }

  private static let formatter1 = NSDateFormatter().then {
    $0.locale = NSLocale(localeIdentifier: "en_US_POSIX")
    $0.dateFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'"
    $0.timeZone = NSTimeZone(abbreviation: "UTC")
  }

  private static let formatter2 = NSDateFormatter().then {
    $0.dateFormat = "yyyy-MM-dd HH:mm:ss Z"
  }

  public static func date(string string: String) -> NSDate? {
    return string.rangeOfString(" ") == nil
    ? formatter1.dateFromString(string)
    : formatter2.dateFromString(string)
  }

  public static func string(date date: NSDate) -> String {
    return basicFormatter.stringFromDate(date)
  }
}