Date Format in Swift
Swift - 5.0
let date = Date()
let format = date.getFormattedDate(format: "yyyy-MM-dd HH:mm:ss") // Set output format
extension Date {
func getFormattedDate(format: String) -> String {
let dateformat = DateFormatter()
dateformat.dateFormat = format
return dateformat.string(from: self)
}
}
Swift - 4.0
2018-02-01T19:10:04+00:00 Convert Feb 01,2018
extension Date {
static func getFormattedDate(string: String , formatter:String) -> String{
let dateFormatterGet = DateFormatter()
dateFormatterGet.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
let dateFormatterPrint = DateFormatter()
dateFormatterPrint.dateFormat = "MMM dd,yyyy"
let date: Date? = dateFormatterGet.date(from: "2018-02-01T19:10:04+00:00")
print("Date",dateFormatterPrint.string(from: date!)) // Feb 01,2018
return dateFormatterPrint.string(from: date!);
}
}
You have to declare 2 different NSDateFormatters
, the first to convert the string to a NSDate
and the second to print the date in your format.
Try this code:
let dateFormatterGet = NSDateFormatter()
dateFormatterGet.dateFormat = "yyyy-MM-dd HH:mm:ss"
let dateFormatterPrint = NSDateFormatter()
dateFormatterPrint.dateFormat = "MMM dd,yyyy"
let date: NSDate? = dateFormatterGet.dateFromString("2016-02-29 12:24:26")
print(dateFormatterPrint.stringFromDate(date!))
Swift 3 and higher:
From Swift 3 NSDate
class has been changed to Date
and NSDateFormatter
to DateFormatter
.
let dateFormatterGet = DateFormatter()
dateFormatterGet.dateFormat = "yyyy-MM-dd HH:mm:ss"
let dateFormatterPrint = DateFormatter()
dateFormatterPrint.dateFormat = "MMM dd,yyyy"
if let date = dateFormatterGet.date(from: "2016-02-29 12:24:26") {
print(dateFormatterPrint.string(from: date))
} else {
print("There was an error decoding the string")
}
This may be useful for who want to use dateformater.dateformat
;
if you want 12.09.18
you use dateformater.dateformat = "dd.MM.yy"
Wednesday, Sep 12, 2018 --> EEEE, MMM d, yyyy
09/12/2018 --> MM/dd/yyyy
09-12-2018 14:11 --> MM-dd-yyyy HH:mm
Sep 12, 2:11 PM --> MMM d, h:mm a
September 2018 --> MMMM yyyy
Sep 12, 2018 --> MMM d, yyyy
Wed, 12 Sep 2018 14:11:54 +0000 --> E, d MMM yyyy HH:mm:ss Z
2018-09-12T14:11:54+0000 --> yyyy-MM-dd'T'HH:mm:ssZ
12.09.18 --> dd.MM.yy
10:41:02.112 --> HH:mm:ss.SSS
Here are alternatives:
- era: G (AD), GGGG (Anno Domini)
- year: y (2018), yy (18), yyyy (2018)
- month: M, MM, MMM, MMMM, MMMMM
- day of month: d, dd
- day name of week: E, EEEE, EEEEE, EEEEEE