Reputation: 6291
I've got a string
containing a date
in this format:
Thu, 04 Sep 2014 10:50:12 +0000
Do you know how can I convert it to: 04-09-2014 (dd-MM-yyyy)
of course, using Swift
Upvotes: 3
Views: 12758
Reputation: 1124
From iOS 15, we can convert in this way:
let strategy = Date.ParseStrategy(format: "\(weekday: .abbreviated), \(day: .twoDigits) \(month: .abbreviated) \(year: .defaultDigits) \(hour: .twoDigits(clock: .twentyFourHour, hourCycle: .zeroBased)):\(minute: .twoDigits):\(second: .twoDigits) \(timeZone: .iso8601(.short))", timeZone: .current)
if let date = try? Date("Thu, 04 Sep 2014 10:50:12 +0000", strategy: strategy) {
// 04-09-2014
let dateString = "\(date.formatted(.dateTime.day(.twoDigits)))-\(date.formatted(.dateTime.month(.twoDigits)))-\(date.formatted(.dateTime.year()))"
}
Upvotes: 0
Reputation: 1455
If the above doesn't work, this should do the trick:
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "US_en")
formatter.dateFormat = "E, dd MMM yyyy HH:mm:ss Z"
let date = formatter.date(from: "Thu, 04 Sep 2014 10:50:12 +0000")
Upvotes: 18
Reputation: 31323
I know the answer to this question has already been accepted but the shown method in that answer doesn't exactly output the date in the format of dd-MM-yyyy. So I'm gonna post this anyway so someone might find it useful.
One of the cool features of Swift is extensions. So I'm gonna create this as an extention so that it's reusable.
Create a extension for NSDate
and put this code in there.
import Foundation
extension NSDate {
convenience init(dateString: String) {
let dateStringFormatter = NSDateFormatter()
dateStringFormatter.dateFormat = "E, dd MMM yyyy HH:mm:ss Z"
dateStringFormatter.timeZone = NSTimeZone(name: "GMT")
let date = dateStringFormatter.dateFromString(dateString)
self.init(timeInterval:0, sinceDate:date!)
}
func getDatePart() -> String {
let formatter = NSDateFormatter()
formatter.dateFormat = "dd-MM-yyyy"
formatter.timeZone = NSTimeZone(name: "GMT")
return formatter.stringFromDate(self)
}
}
And this is how you use it.
NSDate(dateString: "Thu, 04 Sep 2014 10:50:12 +0000").getDatePart()
Output: 04-09-2014
You can change the formats in both functions to accept and output dates in various formats.
Upvotes: 8
Reputation: 14904
Try something like this:
let mydateFormatter = NSDateFormatter()
mydateFormatter.dateFormat = "EEE, MMM d, YYYY hh:mm:ss.SSSSxxx"
let date = mydateFormatter.dateFromString(yourdatestring)
Check out for the current date format if its not working: http://userguide.icu-project.org/formatparse/datetime/
Upvotes: 1