How can I convert this string "2016-04-14T10:44:00+0000"
into an NSDate
and keep only the year, month, day, hour?
The T
in the middle of it really throws off what I am used to when working with dates.
Convert Month Day Year String To Date In Swift import Foundation let dateString = "January 20, 2020" let dateFormatter = DateFormatter() dateFormatter. locale = Locale(identifier: "en_US_POSIX") dateFormatter. dateFormat = "MMMM d, yyyy" if let date = dateFormatter.
Using strptime() , date and time in string format can be converted to datetime type. The first parameter is the string and the second is the date time format specifier. One advantage of converting to date format is one can select the month or date or time individually.
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?
We start by creating a Date object. To convert the date to a string, we need to create a date formatter, an instance of the DateFormatter class. To convert the Date object to a string, we invoke the date formatter's string(from:) instance method.
Convert the ISO8601 string to date
let isoDate = "2016-04-14T10:44:00+0000" let dateFormatter = DateFormatter() dateFormatter.locale = Locale(identifier: "en_US_POSIX") // set locale to reliable US_POSIX dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ" let date = dateFormatter.date(from:isoDate)!
Get the date components for year, month, day and hour from the date
let calendar = Calendar.current let components = calendar.dateComponents([.year, .month, .day, .hour], from: date)
Finally create a new Date
object and strip minutes and seconds
let finalDate = calendar.date(from:components)
Consider also the convenience formatter ISO8601DateFormatter
introduced in iOS 10 / macOS 12:
let isoDate = "2016-04-14T10:44:00+0000" let dateFormatter = ISO8601DateFormatter() let date = dateFormatter.date(from:isoDate)!
Try the following date Format.
let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ssZZZ" let date = dateFormatter. dateFromString (strDate)
Hope it helps..
Swift 4.1 :
let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ssZZZ" let date = dateFormatter.date(from: strDate)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With