Shobhakar Tiwari
Shobhakar Tiwari

Reputation: 7892

Calculate date time by adding / subtracting local offset [ Convert any date time , to UTC time format]

I am getting Flight :

  1. Scheduled Date and Scheduled Time and flight local offset value in service

Now it is required to find the difference between my datetime ( local timezone ) and the datetime ( coming from service ).

Problem : Difference B/W between my local datetime and Flight Scheduled Date and Time ( could be of any TIMEZONE , so in the service i am getting LOCALOFFSET VALUE like : "-7:00" or "-6:00"

E.g : Flight DateTime : 2018-12-28 05:15:00 , Local offset : -06:00 My Local DateTime : 2018-12-28 14:08:00

Need to find the difference ?

Thanks

Upvotes: 1

Views: 790

Answers (1)

Shobhakar Tiwari
Shobhakar Tiwari

Reputation: 7892

Solved this by using localoffset coming from service and with the method available in swift , TimeZone(secondsFromGMT:offset) :

func findFlightTimeInUTCFormat(dateString:String, localOffSet:String) -> Date? {
        let gmtTimeString = dateString

        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
        formatter.timeZone = TimeZone(secondsFromGMT: -6*60*60)
        var finalDate:Date?
        // original string in GMT
        guard let date = formatter.date(from: gmtTimeString) else {
            print("can't convert time string")
            return finalDate
        }
        finalDate = date
        return finalDate
    }

Solved and its working fine.

Upvotes: 1

Related Questions