It seems that NSDateFormatter
has a \"feature\" that bites you unexpectedly: If you do a simple \"fixed\" format operation such as:
NSDateForma
Here is the solution for that problem in the swift version. In swift we can use extension instead of category. So, Here I have created the extension for the DateFormatter and inside that initWithSafeLocale returns the DateFormatter with the relevant Locale, Here in our case that is en_US_POSIX, Apart from that also provided couple of date formation methods.
Swift 4
extension DateFormatter {
private static var dateFormatter = DateFormatter()
class func initWithSafeLocale(withDateFormat dateFormat: String? = nil) -> DateFormatter {
dateFormatter = DateFormatter()
var en_US_POSIX: Locale? = nil;
if (en_US_POSIX == nil) {
en_US_POSIX = Locale.init(identifier: "en_US_POSIX")
}
dateFormatter.locale = en_US_POSIX
if dateFormat != nil, let format = dateFormat {
dateFormatter.dateFormat = format
}else{
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
}
return dateFormatter
}
// ------------------------------------------------------------------------------------------
class func getDateFromString(string: String, fromFormat dateFormat: String? = nil) -> Date? {
if dateFormat != nil, let format = dateFormat {
dateFormatter = DateFormatter.initWithSafeLocale(withDateFormat: format)
}else{
dateFormatter = DateFormatter.initWithSafeLocale()
}
guard let date = dateFormatter.date(from: string) else {
return nil
}
return date
}
// ------------------------------------------------------------------------------------------
class func getStringFromDate(date: Date, fromDateFormat dateFormat: String? = nil)-> String {
if dateFormat != nil, let format = dateFormat {
dateFormatter = DateFormatter.initWithSafeLocale(withDateFormat: format)
}else{
dateFormatter = DateFormatter.initWithSafeLocale()
}
let string = dateFormatter.string(from: date)
return string
} }
usage description:
let date = DateFormatter.getDateFromString(string: "11-07-2001”, fromFormat: "dd-MM-yyyy")
print("custom date : \(date)")
let dateFormatter = DateFormatter.initWithSafeLocale(withDateFormat: "yyyy-MM-dd HH:mm:ss")
let dt = DateFormatter.getDateFromString(string: "2001-05-05 12:34:56")
print("base date = \(dt)")
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let dateString = dateFormatter.string(from: Date())
print("dateString = " + dateString)
let date1 = dateFormatter.date(from: "2001-05-05 12:34:56")
print("date1 = \(String(describing: date1))")
let date2 = dateFormatter.date(from: "2001-05-05 22:34:56")
print("date2 = \(String(describing: date2))")
let date3 = dateFormatter.date(from: "2001-05-05 12:34:56PM")
print("date3 = \(String(describing: date3))")
let date4 = dateFormatter.date(from: "2001-05-05 12:34:56 PM")
print("date4 = \(String(describing: date4))")