Last active
December 16, 2015 13:38
-
-
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)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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