Search code examples
iosswiftdatecalendartimezone

Convert date with timezone


I am getting date from server: 2022-12-14 20:59:59 +0000 I have view with promo codes, so according to received date I should show after how many seconds it will be expired.

For example if my current date is 2022-12-14 19:59:59 +0000, I must show 60:00 seconds. If the users timezone is GMT+4, he must see 60:00 seconds as well.

So I use this code:

 let currentTime = Int(Date().timeIntervalSince1970)
 let expirationDate = model.expirationDate

 expiredText = expirationDate.dateStringWithFormat("dd.MM.yyyy")
 timeLeft = Int(expirationDate.timeIntervalSince1970) - currentTime
           

Result is: currentTime: 2022-12-14 13:48:16 +0000 // my current time is 16:48:16

expirationDate: 2022-12-14 20:59:59 +0000

timeLeft: "0d. 07:11:43"

So Date() returns wrong date.

I tried to use calendar, but result is the same.

let calendar = Calendar(identifier: .gregorian)
let currentDate = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss:Z"
dateFormatter.timeZone = calendar.timeZone

How can I correctly convert my timezone to timezone of received date or vice versa? Thanks


Solution

  • I think you are making this more complicated than it is.

    We have a server timestamp

    let serverDate = "2022-12-14 20:59:59 +0000"
    

    that we convert to a Date using a formatter

    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ssZ"
    

    Then we want to calculate the difference between the server data and now

    if let expirationDate = dateFormatter.date(from: serverDate) {
        let components = Calendar.current.dateComponents([.day, .hour, .minute, .second], from: .now, to: expirationDate)
    }
    

    and then we can use a DateComponentsFormatter to get the difference as a string

    let compFormatter = DateComponentsFormatter()
    print(compFormatter.string(from: components))