Why I Can't Convert String to Date in Swift

Why I can't convert string to date in Swift?

Your date is 24 hour format So it should be HH not hh, so change your date formate to yyyy-MM-dd HH:mm:ss.

let string = "2017-02-23 15:26:00"
let df = DateFormatter()
df.dateFormat = "yyyy-MM-dd HH:mm:ss"
let result = df.date(from: string)

Unable to convert string to date and date to string Swift 5.2

Try to use this format (HH instead of hh):

dateFormatter.dateFormat = "EEE, dd MMM yyyy HH:mm:ss Z"
  • hh - "The 12-hour hour padding with a zero if there is only 1 digit"
  • HH - "The 24-hour hour padding with a zero if there is only 1 digit"

Convert string containing date to Date

In addition to the Date being shown as an Optional, your format string appears to be wrong. "YYYY" should be "yyyy", so the whole line that assigns the formatter should be:

dateFormatter.dateFormat = "MMM d, yyyy hh:mma z"

That change yields the output

"Optional(2022-01-18 16:39:00 +0000)"

In addition, you should really force the calendar to Gregorian or iso8601, and set its locale to "en_US_POSIX:

An improved version of the date formatter could would look like this:

(from Leo's edit.)

let str = "Jan 18, 2022 04:39PM GMT"
let dateFormatter = DateFormatter()
dateFormatter.calendar = .init(identifier: .iso8601)
dateFormatter.locale = .init(identifier: "en_US_POSIX")
dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)
dateFormatter.dateFormat = "MMM d, yyyy hh:mma z"

if let date = dateFormatter.date(from: str) {
let dateString = dateFormatter.string(from: date)
print(dateString == str) // true
}

Convert string to date in Swift

  • 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 10.12:

let isoDate = "2016-04-14T10:44:00+0000"

let dateFormatter = ISO8601DateFormatter()
let date = dateFormatter.date(from:isoDate)!

Can't Convert Date Format Into Display Date In Swift

You should always set your dateFormat locale to "en_US_POSIX" before setting the dateFormat. Btw it looks like that your date string you are reading from database is always in UTC format, if that is the case you should set your dateFormatter timezone to zero secondsFromGMT and escape your date string timezone:

let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSSIX")
dateFormatter.dateFormat = "EEE MMM dd yyyy HH:mm:ss 'GMT+0000 (Greenwich Mean Time)'"
dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)
dateFormatter.date(from: "Thu Nov 12 2020 07:00:00 GMT+0000 (Greenwich Mean Time)")

You should also create a static date formatter to avoid creating a new one every time you call this method:



extension Formatter {
static let customDate: DateFormatter = {
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSSIX")
dateFormatter.dateFormat = "EEE MMM dd yyyy HH:mm:ss 'GMT+0000 (Greenwich Mean Time)'"
dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)
return dateFormatter
}()
static let yyyyMMMd: DateFormatter = {
let dateFormatter = DateFormatter()
dateFormatter.setLocalizedDateFormatFromTemplate("yyyyMMMd")
return dateFormatter
}()
}


extension String {
func convertToDate() -> Date? {
Formatter.customDate.date(from: self)
}
func convertToDisplayFormat() -> String {
convertToDate()?.convertToMonthDayTimeFormat() ?? "N/A"
}
}


extension Date {
func convertToMonthDayTimeFormat() -> String {
Formatter.yyyyMMMd.string(from: self)
}
}

Playground testing:

"Thu Nov 12 2020 07:00:00 GMT+0000 (Greenwich Mean Time)".convertToDisplayFormat()  // "Nov 12, 2020"

Can't converting String to NSDate Swift

dateFormatter.dateFormat should match the date string you are passing.

check this Date Format in Swift



Related Topics



Leave a reply



Submit