Convert Date String Swift

Convert NSDate to String in iOS Swift

you get the detail information from Apple Dateformatter Document.If you want to set the dateformat for your dateString, see this link , the detail dateformat you can get here
for e.g , do like

let formatter = DateFormatter()
// initially set the format based on your datepicker date / server String
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"

let myString = formatter.string(from: Date()) // string purpose I add here
// convert your string to date
let yourDate = formatter.date(from: myString)
//then again set the date format whhich type of output you need
formatter.dateFormat = "dd-MMM-yyyy"
// again convert your date to string
let myStringDate = formatter.string(from: yourDate!)

print(myStringDate)

you get the output as

enter image description here

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)!

Convert date string swift

The standard ISO8601 date format with fractional seconds and time zone is

yyyy-MM-dd'T'HH:mm:ss.SSSZ

let myDate = "2016-06-20T13:01:46.457+02:00"
let dateFormatter = NSDateFormatter()
dateFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX") // edited
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
let date = dateFormatter.dateFromString(myDate)!
dateFormatter.dateFormat = "dd/MM/yyyy"
let dateString = dateFormatter.stringFromDate(date)

Swift 3:

let myDate = "2016-06-20T13:01:46.457+02:00"
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX") // edited
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
let date = dateFormatter.date(from:myDate)!
dateFormatter.dateFormat = "dd/MM/yyyy"
let dateString = dateFormatter.string(from:date)

In macOS 10.13+, iOS 11+ ISO8601DateFormatter is an alternative as input formatter

let myDate = "2016-06-20T13:01:46.457+02:00"
let inputFormatter = ISO8601DateFormatter()
inputFormatter.formatOptions = [.withFullDate, .withFullTime, .withFractionalSeconds]
let date = dateFormatter.date(from:myDate)!
let outputFormatter = DateFormatter()
outputFormatter.locale = Locale(identifier: "en_US_POSIX")
outputFormatter.dateFormat = "dd/MM/yyyy"
let dateString = dateFormatter.string(from:date)

Convert date from string iOS swift 5

The Unicode LDML date format doesn't support GMT+0000 (however it supports GMT+00:00) nor strings like (Coordinated Universal Time)

A possible solution is to remove the non-standard parts from the string with Regular Expression

let dateFormat = "E MMM dd yyyy HH:mm:ss Z"

let isoDate = "Wed Oct 14 2020 05:31:08 GMT+0000 (Coordinated Universal Time)"

let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.dateFormat = dateFormat
dateFormatter.timeZone = TimeZone(identifier: "UTC")
let trimmedIsoDate = isoDate.replacingOccurrences(of: "GMT([+-]\\d{4})\\s\\([^)]+\\)", with: "$1", options: .regularExpression)
print(dateFormatter.date(from: trimmedIsoDate))

The pattern captures the +0000 part and replaces everything from GMT to the end with the captured time zone

Converting a String to a Date in Swift

The date format needs to be for the string you are trying to convert, not the format you want back

so

formatter.dateFormat = "dd MM YYYY"

should be

formatter.dateFormat = "E, d MMM yyyy HH:mm:ss Z"

How to convert string date time format to another format using Swift

extension String {
func convertToDateFormate(current: String, convertTo: String) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = current
guard let date = dateFormatter.date(from: self) else {
return self
}
dateFormatter.dateFormat = convertTo
return dateFormatter.string(from: date)
}
}

convert to required formate as

let dateString = "12-10-2019"
let convertedDate = dateString.convertToDateFormate(current: "dd-MM-YYYY", convertTo: "YYYY-MM-dd")

How can I convert string date to NSDate?

try this:

let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = /* find out and place date format from
* http://userguide.icu-project.org/formatparse/datetime
*/
let date = dateFormatter.dateFromString(/* your_date_string */)

For further query, check NSDateFormatter and DateFormatter classes of Foundation framework for Objective-C and Swift, respectively.

Swift 3 and later (Swift 4 included)

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = /* date_format_you_want_in_string from
* http://userguide.icu-project.org/formatparse/datetime
*/
guard let date = dateFormatter.date(from: /* your_date_string */) else {
fatalError("ERROR: Date conversion failed due to mismatched format.")
}

// use date constant here


Related Topics



Leave a reply



Submit