0

I am looking into a bug in my birthday app. The member .day of Date returns the wrong day but curiously only in the timezone UTC-4. .year and .month are totally fine too. Are there any other ways to get the day of the month from a date reliably in any given timezone?

let birthday = Date().midnightUTC() // 2002-01-12 00:00:00 +0000

func upcomingBirthday() -> Date {
        var dc = DateComponents()
        dc.calendar = .current
        dc.year = Date().year
        dc.month = birthday.month
        dc.day = birthday.day
        
        print("Date Day: \(birthday.day)") // 10

        let today = Date().midnightUTCDate()

        if dc.date! == today {
            return today
        } else if dc.date!.midnightUTCDate().isEarlierThan(today) {
            dc.year! += 1
            return dc.date!            
        } else {
            return  dc.date!.midnightUTCDate()
        }
    }
7
  • In general, you should be trying to compare your dates within the same timezone, so maybe, converting both Dates to UTC, for example Commented Jan 12, 2022 at 21:41
  • 2
    Don't store it as date. Store it as date components
    – Leo Dabus
    Commented Jan 12, 2022 at 21:44
  • @MadProgrammer I don't think that's the correct approach. The guy can be anywhere in the world when it is his birthday regardless where he/she were born
    – Leo Dabus
    Commented Jan 12, 2022 at 21:46
  • Don't use UTC. Use the device timezone.
    – Leo Dabus
    Commented Jan 12, 2022 at 21:47
  • @LeoDabus But there's your problem, you've got one date in UTC and one date in local time zone - this allows for the UTC day to be before or after the local date, so you need to start with a common baseline Commented Jan 12, 2022 at 21:54

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.