Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift date components incorrect return of date day number

Tags:

date

swift

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

like image 824
Nicola Rigoni Avatar asked Oct 16 '25 13:10

Nicola Rigoni


1 Answers

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.

like image 145
burnsi Avatar answered Oct 18 '25 09:10

burnsi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!