How do you create a date object from a date in Swift xcode?


Coming from Objective C- Background now we don’t need to use NSDate as Swift has defined its own struct type Date. Date bridges to the NSDate class. You can use these interchangeably in code that interacts with Objective-C APIs.

To read more about Date you can check official apple docs https://developer.apple.com/documentation/foundation/date

In this post we will be seeing how one can create date object, So let’s get started we will be using Playground for this purpose.

First, we will be seeing how to get the current date and time (UTC), to get current date and time, create an object of Date, enter the below code in the playground to see the results.

let currentDateAndTime = Date()
print(currentDateAndTime)

This is the easiest way to create a date object.

Now we will be seeing a second way to create the data object i.e. by using Date Formatter.

To read more about it,https://developer.apple.com/documentation/foundation/date

let stringDate = "2019-10-10"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let date = dateFormatter.date(from: stringDate)
print(date ?? "")

Using this we can convert the date as we want.

The third way to create the data object is using Date Components,

var date = DateComponents()
date.year = 2019
date.month = 12
date.day = 12
date.timeZone = TimeZone(abbreviation: "IST")
date.hour = 12
date.minute = 34
date.second = 55
let userCalendar = Calendar.current
let dateAndTime = userCalendar.date(from: date)
print(someDateTime ?? "")

Updated on: 30-Aug-2019

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements