Skip to content

Instantly share code, notes, and snippets.

@xiel
Last active December 16, 2015 13:38
Show Gist options
  • Save xiel/ed6f61e695836be3620c to your computer and use it in GitHub Desktop.
Save xiel/ed6f61e695836be3620c to your computer and use it in GitHub Desktop.
Transform JS Date String to NSDate or localizedString | supports JavaScript/ECMAScript Date Time String Format (simplification of the ISO 8601)
//
// NSDateFormatter extension
// Transform JS Date String to NSDate or localizedString
//
// Created by Felix Leupold on 16.12.15 © 2015 XIEL development.
// License: WTFPL / MIT
//
// Usage Examples:
// NSDateFormatter.dateFromJsDateString("2015-11-22T16:09:19.000Z");
// NSDateFormatter.localizedStringFromJsDateString("2015-11-22T16:09:19.000Z");
// NSDateFormatter.localizedStringFromJsDateString("2015-11-22T16:09:19.000Z", dateStyle: .ShortStyle, timeStyle: .ShortStyle)
import Foundation
extension NSDateFormatter {
static func dateFromJsDateString(jsDateString: String) -> NSDate? {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
if let date = dateFormatter.dateFromString(jsDateString) {
return date
}
return nil
}
static func localizedStringFromJsDateString(jsDateString: String) -> String? {
return NSDateFormatter.localizedStringFromJsDateString(jsDateString, dateStyle: .ShortStyle, timeStyle: .NoStyle)
}
static func localizedStringFromJsDateString(jsDateString: String, dateStyle: NSDateFormatterStyle, timeStyle: NSDateFormatterStyle) -> String? {
if let date = NSDateFormatter.dateFromJsDateString(jsDateString) {
let dateFormatted = NSDateFormatter.localizedStringFromDate(date, dateStyle: dateStyle, timeStyle: timeStyle)
return dateFormatted
}
return nil
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment