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

iOSiPhone/iPadMobile Development

To create a date object in swift we’ll use DateComponents() of swift. We can do this In two ways. We’ll use Playground to test our code instead of simulator.

We’ll use date component and calendar to create a date. We can create date component in two ways.

Method 1

Creating date using the default initializer of DateComponent().

var date = DateComponents.init(
calendar: <#T##Calendar?#>,
timeZone: <#T##TimeZone?#>,
era: <#T##Int?#>,
year: <#T##Int?#>,
month: <#T##Int?#>,
day: <#T##Int?#>,
hour: <#T##Int?#>,
minute: <#T##Int?#>,
second: <#T##Int?#>,
nanosecond: <#T##Int?#>,
weekday: <#T##Int?#>, weekdayOrdinal: <#T##Int?#>, quarter: <#T##Int?#>,
weekOfMonth: <#T##Int?#>, weekOfYear: <#T##Int?#>, yearForWeekOfYear: <#T##Int?#>)

This will ask all the things like calendar type, date, day, month, year and other things required to create a date.

Method 2

We can create the same using only init method of DateComponent()

var date = DateComponents()
date.day = 5
date.month = 6
date.year = 1993

These are the two ways to create date component, now we need to convert date components to date. We can do it by using the below code.

let cal = Calendar.current
let newDate = cal.date(from: date)
print("the date is", newDate!)

When we run the above code result would be

raja
Published on 04-Apr-2019 16:05:03
Advertisements