Search code examples
swiftdatensdateformattercloudkit

Why my Cloud records Time isn't the same when I load it into my app


In a training project to learn the cloudKit capacity I record a date via a Datepicker and I save it into a cloudKit data base. I use the French format "DD/MM/YYYY HH:MM". Everything work fine and the date which is entered by the user is the same format in the data base.

Now I would like to work with this date in an other view in my app. So I load it into an array from cloudKit and I would like to compare it with the current time.

let recordTime = LastMealRecords[LastMealRecords.count - 1]
    
let currentSavedTime = (recordTime.object(forKey: "Timming"))
let diffComponents = Calendar.current.dateComponents([.hour], from: currentSavedTime as! Date, to: Now)
let intervals = diffComponents.hour
print(Now)
print(currentSavedTime)

So here the print show :

Now : DD/MM/YYYY HH:MM (which is the correct local time !)
currentSavedTime : DD/MM/YYY HH:MM (but HH:MM is not the same value as the one which is save on the Cloud data base. In fact it seem to be the UTC time cause there is 2h difference in less like the Local and UTC time in France... )

Question : How could I fixe this matter ? I'm trying to find the same value which is saved on the cloud..

Thanks for your help !


Solution

  • You can't make changes to the time saved at server end, all you can do is manipulate your current time accordingly

    // Return time zone used by the system right away

    let timeZone = NSTimeZone.system
    

    // Returns the difference in seconds between the server and GMT at a given date.

     let timeZoneOffset = timeZone.secondsFromGMT(for: currentDate) / 3600
    
     print(timeZoneOffset, "hours offset for timezone", timeZone)