Home > Back-end >  How do I programatically determine the time (hours/minutes) and set them to 00/00 in Swift?
How do I programatically determine the time (hours/minutes) and set them to 00/00 in Swift?

Time:11-05

I am doing some date math and before doing so am trying to programatically adjust the time associated with a date based on its current value. In the code below I am able to set the hours and minutes to 00/00 but I have to know the offset and manually set the value. Below is my code and next to each print statement I have listed the value I am getting. Any assistance in pointing out the error I am making will be appreciated. I wonder if it is a timezone issue relative to GMT.

Chris

func AdjustDateTime(vooDate: Date) -> Date {
    
    let date = vooDate
    let _ = print("date")
    let _ = print(date)          // returns 2021-10-25 06:00:00  000
    let calendar = Calendar.current
    let components = calendar.dateComponents([.year, .month, .day, .hour, .minute], from: date)
    let year = components.year
    let month = components.month
    let day = components.day
    let hour = components.hour
    let minute = components.minute
    
    let _ = print("hour")
    let _ = print(hour!)          // returns 0 even though the date above say 06
    let _ = print("minute")
    let _ = print(minute!)        // returns 0

    var comps = DateComponents()
    comps.year = year
    comps.month = month
    comps.day = day!   1
    comps.hour = -06              // setting manually, would like to do so programatically
    comps.minute = 00
    
    let returnDate: Date = Calendar.current.date(from: comps)!
    
    let _ = print("Return Date")
    let _ = print(returnDate)     // returns 2021-10-26 00:00:00  0000, which is what I want
    
    return returnDate
    
}

CodePudding user response:

Setting the time zone as indicated by Jacob was the key to solving the problem. In the code where I read in the JSON file I modified my dateFormatter to what's shown below. This returns a date object as shown below the code. Now I do not need to worry about the hours, since they are 0. From there it is easy to add 1 day with a function, shown below. Before doing my date math I make the same adjustments to a date in the future, i.e. timezone and locale, and I get the correct difference between the two dates which was the ultimate goal. Thank you for the assistance.

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
dateFormatter.locale = Locale(identifier: "en_US_POSIX") // added
dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)     // added

2021-10-25 00:00:00  0000


func AdjustDateTime(vooDate: Date) -> Date {
    
  return Calendar.current.date(byAdding: .day, value: 1, to: vooDate)!
}



  • Related