Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string to date in Swift

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.

like image 549
asheyla Avatar asked Apr 26 '16 10:04

asheyla


People also ask

How do I convert a string to a date in Swift?

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.

How do I convert a string to a date?

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.

How do I change the date format in swift 5?

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?

How do I change the current date format in Swift?

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.


2 Answers

  • 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)! 
like image 74
vadian Avatar answered Dec 05 '22 09:12

vadian


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) 
like image 22
Balaji Ramakrishnan Avatar answered Dec 05 '22 09:12

Balaji Ramakrishnan