A DateFormatter that converts between dates and their textual representations.
You can find more Locale
identifier here.
- first, convert your date to local time zone. using a
Locale
class
- after you can covert the date in specific formate.
And try this code.
let dateStr = "Wed, 26 Jul 2017 18:10:02 +0530"
if let date = Date(fromString: dateStr, format: "MMM dd, yyyy hh:mm:ss a") {
debugPrint(date.toString(format: "dd-MM-yyyy HH:ii"))
}
Date Extension is ...
extension Date {
// Initializes Date from string and format
public init?(fromString string: String, format: String, identifier: String = Locale.current.identifier) {
let formatter = DateFormatter()
formatter.dateFormat = format
formatter.locale = Locale(identifier: identifier)
if let date = formatter.date(from: string) {
self = date
} else {
return nil
}
}
// Converts Date to String, with format
public func toString(format: String, identifier: String = Locale.current.identifier) -> String {
let formatter = DateFormatter()
formatter.locale = Locale(identifier: identifier)
formatter.dateFormat = format
return formatter.string(from: self)
}
}
String Extension is ...
extension String {
// Converts String to formated date string, with inputFormat and outputFormat
public func toDate(form inputFormat: String, to outputFormat: String, identifier: String = Locale.current.identifier) -> String? {
return Date(fromString: self, format: inputFormat, identifier: identifier)?.toString(format: outputFormat, identifier: identifier)
}
// Converts String to Date, with format
func toDate(format: String, identifier: String = Locale.current.identifier) -> Date? {
return Date(fromString: self, format: format, identifier: identifier)
}
}
translatedDate
is nil, I tried in playground, no issue. So, an issue with local? Else, I don't the theii
in the format (unicode.org/reports/tr35/tr35-31/…), I don't know what you want to do with it, so if you pass theif let
test, I don't think thatdateFormatter.string(from: translatedDate)
will be what you want. – ServicemandateFormatter.locale = Locale(identifier: "en_US_POSIX")
" issue, compare #40692878 or #6613610 – but what doesii
stand for? – Depravity8
will not matchhh
, becausehh
expects two digits (so08
). Try a singleh
instead. – Doscherlet datetime = "Dec 31, 2017 8:00:00 PM" let dateFormatter = DateFormatter() dateFormatter.dateFormat = "MMM dd, yyyy hh:mm:ss a" dateFormatter.locale = Locale(identifier: "en_US_POSIX") if let translatedDate = dateFormatter.date(from: datetime) { dateFormatter.dateFormat = "dd-MM-yyyy HH:mm" let result = dateFormatter.string(from: translatedDate) print(result) // 31-12-2017 20:00 }
anyway, I thinkii
is a mistake – Roboth
matches any hour from 1 to 12. – Depravity