How can I convert string date to NSDate?


In Swift, you can use the DateFormatter class to convert a string date to a date object. This class provides date conversion properties and methods. In this article, we will see some examples of date conversions.

DateFormatter Class

Swift's standard library has a class that is used to convert dates. It may be used to change a string into a date object and the other way around. To parse date objects in various formats, this class offers attributes and methods.

You must build an object of the DateFormatter class in order to transform a string to a date object and vice versa. The date format for the target format string may then be specified using the dateFormat attribute. The string(from:) function may thus be used to turn a date object into a string with a specified format.

We may construct a DateFormatter instance, adjust its dateFormat property to match the format of the input string date, and then use the date(from:) method on the date formatter with the input string date as an argument to convert a textual representation of a date to a Date object. The optional Date object that is returned by this must be carefully unwrapped using an if let clause or another optional binding syntax.

Some examples of format characters used in a dateFormat string include

  • yyyy for a four-digit year

  • MM for a two-digit month

  • dd for a two-digit day of the month

  • HH for a two-digit hour in 24-hour format

  • mm for a two-digit minute

  • ss for a two-digit second

  • a for an AM/PM indicator

  • zzz for a three-letter timezone abbreviation

  • Z for the timezone offset in the format +/-HHmm

The dateFormat field of a DateFormatter object is a string that specifies the format of the date and time representation. Using a mixture of format characters, it defines any delimiters or text that should be included, as well as which pieces of the date and time should be included in the output string.

Setting the locale, timezone, and calendar that will be used for conversion are just a few of the additional attributes and methods that DateFormatter offers for modifying the behavior of date formatting and parsing. Generally speaking, DateFormatter is a helpful class for managing various date formats and standards when working with dates and times in Swift.

Algorithms

  • Step 1 − Create a date string object

  • Step 2 − Create an instance of the DateFormatter class

  • Step 3 − Assign the date format using the dateFormat property

  • Step 4 − Assign the timezone

  • Step 5 − Convert the string to a date object using the date(from) method

  • Step 6 − Print the date object on the console

Example 1

In this example, we first create a string representation of the date we want to convert ("2022-05-10"). We then create an instance of DateFormatter and set its dateFormat property to match the string date format ("yyyy-MM-dd"). Finally, we call the date(from:) method on the date formatter, passing the string date as an argument. This returns an optional Date object, which can be used in our code.

import Foundation
let dateString = "2022-05-10"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
dateFormatter.timeZone = TimeZone(identifier: "UTC")
if let dateObject = dateFormatter.date(from: dateString) {
   print("Date in string: \(dateString)")
   print("Date object: \(dateObject)")
}

Output

Date in string: 2022-05-10
Date object: 2022-05-10 00:00:00 +0000

Example 2

In this example, we create a DateFormatter instance with a custom dateFormat property set to "dd-MM-yyyy HH:mm:ss", which matches the format of the input string date. We then call the date(from:) method on the date formatter with the input string date as a parameter. This returns an optional Date object, which we safely unwrap using an if let statement. Finally, we print the resulting Date object.

import Foundation
let dateString = "10-05-2022 12:30:45"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd-MM-yyyy HH:mm:ss"
dateFormatter.timeZone = TimeZone(identifier: "UTC")
if let dateObject = dateFormatter.date(from: dateString) {
   print("String object: \(dateString)")
   print("Date object: \(dateObject)")
}

Output

String object: 10-05-2022 12:30:45
Date object: 2022-05-10 12:30:45 +0000

Example 3

In this example, we create a DateFormatter instance with a dateFormat property set to "yyyy-MM-dd'T'HH:mm:ssZZZZZ", which matches the format of the input string date with a timezone offset. We then call the date(from:) method on the date formatter with the input string date as a parameter.

import Foundation
let dateString = "2022-05-10T12:30:45-05:00"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"
dateFormatter.timeZone = TimeZone(identifier: "UTC")
if let dateObject = dateFormatter.date(from: dateString) {
   print("String object: \(dateString)")
   print("Date object: \(dateObject)")
}

Output

String object: 2022-05-10T12:30:45-05:00
Date object: 2022-05-10 17:30:45 +0000

Example 4

In this example, we create a DateFormatter instance with a dateFormat property set to "dd-MMM-yyyy", which matches the format of the input string date with an abbreviated month name. We then call the date(from:) method on the date formatter with the input string date as a parameter.

import Foundation
let dateString = "10-May-2022"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd-MMM-yyyy"
dateFormatter.timeZone = TimeZone(identifier: "UTC")
if let dateObject = dateFormatter.date(from: dateString) {
   print("String object: \(dateString)")
   print("Date object: \(dateObject)")
}

Output

String object: 10-May-2022
Date object: 2022-05-10 00:00:00 +0000

Conclusion

In conclusion, converting a string date to a Date object in Swift involves using a DateFormatter instance with a dateFormat property set to match the format of the input string date. Once we have the DateFormatter set up correctly, we can call its date(from:) method with the input string date as a parameter to get an optional Date object. We then need to safely unwrap the optional using an if let statement or other optional binding syntax, and we can use the resulting Date object as needed. With this knowledge, we can easily convert a wide variety of string date formats to Date objects in our Swift code.

Updated on: 24-Apr-2023

466 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements