Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Create date by components in swift

Hello i have a problem: I try to create date by components but it’s give me wrong hours..
For example, I want to have 2022-04-24 00:00:00
Here the code

func createDate(year: Int, month: Int, day: Int, hour: Int, minutes: Int)->Date {
   let calendar = Calendar.current

    var dateComponents = DateComponents()
    dateComponents.year = year
    dateComponents.month = month
    dateComponents.day = day
    dateComponents.hour = hour
    dateComponents.minute = minute

   let date = calendar.date(from: dateComponents)!
   return date
}

let date = createDate(year: 2022, month: 4, day: 24, hour: 0, minute: 0) // return 2022-04-23 22:00:00 +0000

let date2 = createDate(year: 2022, month: 4, day: 24, hour: 9, minute: 0) // return 2022-04-24 7:00:00 +0000

I have 2 hours late.
I’m in France, i set my virtual device in France region.
Do you know where is the error ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Try adding "GMT" timezone, such as:

 dateComponents.timeZone = TimeZone(identifier: "GMT")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading