Search code examples
swiftnsdate

Convert HH:mm string to GMT time string HH:mm


I'm using this code to convert HH:mm string to GMT time string HH:mm:

func convertToGMT(timeString: String) -> String {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "HH:mm"
    
    // Assuming the input time is in the user's local time zone
    dateFormatter.timeZone = TimeZone.current
    
    // Parse the input time string into a Date object
    guard let date = dateFormatter.date(from: timeString) else {
        return "" // Return nil if the input format is invalid
    }
    
    // Convert the date to GMT (UTC) time zone
    dateFormatter.timeZone = TimeZone(abbreviation: "GMT")
    let gmtTimeString = dateFormatter.string(from: date)
    
    return gmtTimeString
}

The problem is that in Jerusalem GMT -3 I get for 12:00 -> 10:00 instead of 09:00.

What is the problem?


Solution

  • The problem is how your converting the date, when you're doing the conversion to date using the date formatter

        // Parse the input time string into a Date object
        guard let date = dateFormatter.date(from: timeString) else {
            return "" // Return nil if the input format is invalid
        }
        
    

    It is producing the following date 2000-01-01 10:00:00 +0000.

    Upon looking on a time zone converter website the result produced below shows that the conversion being done on your current code is correct. enter image description here

    The conversion shown below using current date indicates a difference of 3 hours, which is also the difference you expected your code to produce. This difference is explained by JeremyP in the comments:

    In July, Israel is in daylight savings time. In January it is not. In January of any year including 2000, Israel is two hours ahead of GMT. In July it is three hours ahead.

    enter image description here

    A possible solution is to create the date using DateComponents:

    func convertToGMT(timeString: String) -> String {
        var dateComponents = Calendar.current.dateComponents(
            in: TimeZone.current,
            from: Date()
        )
        
        let dateParts = timeString.split(separator: ":")
        dateComponents.hour = Int(dateParts[0]) // TODO: validate existance on array
        dateComponents.minute = Int(dateParts[1]) // TODO: validate existance on array
        
        // Parse the input time string into a Date object
        guard let date = Calendar.current.date(from: dateComponents) else {
            return "" // Return nil if the input format is invalid
        }
        
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "HH:mm"
        // Convert the date to GMT (UTC) time zone
        dateFormatter.timeZone = TimeZone(abbreviation: "GMT")
        let gmtTimeString = dateFormatter.string(from: date)
        
        return gmtTimeString
    }