Home > Mobile >  How to zero out time for date 90 days ago?
How to zero out time for date 90 days ago?

Time:01-19

I'm trying to create 2 dates. The first is 90 days ago, and the 2nd is now. I can get the 90 days ago date, but I need the time for it to be 00:00:00 0000 and I can't seem to get rid of or zero out the time to make it that. It keeps coming back as 23:00:00 0000. It also appears to give me different dates for 90 days ago?

Here's the code I'm using.

print("LAST NINETY DAYS")
            
            let components = Calendar.current.dateComponents([.year, .month], from: Date())
            let now = Calendar.current.date(from: components)!
            print(now)
            //have to zero out the time
            let days90 = Calendar.current.date(byAdding: .day, value: -90, to: now) ?? Date()
            
            var components2 = Calendar.current.dateComponents([.year, .month], from: days90)
            components2.hour = 0
            components2.minute = 0
            components2.second = 0
            
            let now2 = Calendar.current.date(from: components2)!
            
            print(now2)
            print(Date())
            
            firstAndLastDateObj.firstDate = now2
            
            firstAndLastDateObj.lastDate = Date()

CodePudding user response:

To work exclusively in UTC you have to set the time zone of the calendar to UTC.

Create a custom instance of Calendar:

var cal = Calendar(identifier: .gregorian)
cal.timeZone = TimeZone(secondsFromGMT: 0)!

Then get midnight of the current date and calculate 90 days ago

let todayMidnight = cal.startOfDay(for: Date())
let ninetyDaysAgo = cal.date(byAdding: .day, value: -90, to: todayMidnight)!
  • Related