Home > Blockchain >  Swift date components incorrect return of date day number
Swift date components incorrect return of date day number

Time:09-06

I need to obtain a date from some variable values So I specify year, month and day and I need a Date as return Doing the following works except for the day because it return the day input - 1

let todayDate: Date = Calendar.current.startOfDay(for: Date.from(year: 2022, month: 09, day: 05)!)
print("today date = \(todayDate)")

extension Date {
        
        static func from(year: Int, month: Int, day: Int) -> Date? {
            let calendar = Calendar(identifier: .gregorian)
            var dateComponents = DateComponents()
            dateComponents.year = year
            dateComponents.month = month
            dateComponents.day = day
            return calendar.date(from: dateComponents) ?? nil
        }
    }

And the output is

today date = 2022-09-04 22:00:00  0000

CodePudding user response:

Date and time can be a bit tricky. The Date struct stores a point in time relative to GMT. If you print it it will show exactly that.

Solution:

Don´t use print, use a proper Dateformatter. To illustrate what I mean use this in a playground:

let date = Calendar.current.startOfDay(for: Date())
print(date)
//2022-09-03 22:00:00  0000
// when it is 4.th of september 00:00 in my timezone ( - Daylight saving) it is this time in GMT

let formatter = DateFormatter()
formatter.dateFormat = "dd MM yyyy HH:mm:ss"

print(formatter.string(from: date))
//04 09 2022 00:00:00
// this is the time in my timezone

So the issue here is not that it has the wrong time, it is just not presented in the correct time zone.

  • Related