Search code examples
iosswiftdatetimezonensdateformatter

Convert 12Hr UTC date to 24Hr Local TimeZone format in Swift


As per UTC to IST conversion tool if UTC 12Hr date string is = "2018-12-31 07:35 PM" then it needs to be converted as "2019-01-01 01:05" (24Hr format in IST) [note : here 12Hr IST converted date is "2019-01-01 01:05 AM"]

So how do to convert this 12Hr UTC date into 24Hr IST dateFormat?

current code is :

static func convertUTCdateToLocalTimezoneDate(dateString: String, fromDateFormat: String, toDateFormat: String) -> String {
        if dateString.count > 0 {
            let dateFormatter = DateFormatter()
            let is24Hr: Bool = AppUtility.isSystemTimeFormatIs24Hr(dateString: AppUtility.getIphoneCurrnetTime())
            let fromDateFormatLocal = is24Hr == true ? kDateIn24Format : kDateIn12Format
            dateFormatter.dateFormat = fromDateFormatLocal
            dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
            let date = dateFormatter.date(from: dateString)
            var timeStamp = ""
            dateFormatter.dateFormat = toDateFormat
            dateFormatter.timeZone = NSTimeZone.local
            timeStamp = dateFormatter.string(from: date!)
            return timeStamp
        }
        return ""
    }

static func isSystemTimeFormatIs24Hr(dateString: String) -> Bool {
    let formatter = DateFormatter()
    formatter.locale = NSLocale.current
    formatter.dateStyle = .none
    formatter.timeStyle = .short
    let amRange: NSRange? = (dateString as NSString).range(of: formatter.amSymbol)
    let pmRange: NSRange? = (dateString as NSString).range(of: formatter.pmSymbol)
    let is24h: Bool = amRange?.location == NSNotFound && pmRange?.location == NSNotFound
    return is24h
}

Solution

  • Following code will be resolved your issue

        func dateFormatter() -> Date? {
            let inputDateString = "2018-12-31 07:30:00 PM"
    
            let outFormatter = DateFormatter()
            outFormatter.locale = Locale(identifier: "UTC")
            outFormatter.timeZone = TimeZone(abbreviation: "UTC")
            outFormatter.dateFormat = "yyyy-MM-dd hh:mm:ss a"
    
            let outDate = outFormatter.date(from: inputDateString)
    
            outFormatter.locale = Locale.current
            outFormatter.timeZone = TimeZone.current
            outFormatter.dateFormat = "yyyy-MM-dd hh:mm a"
    
            let date12HrsString = outFormatter.string(from: outDate!)
            print("12 Hrs Format: \(date12HrsString)")
    
            outFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
            let date24HrsString = outFormatter.string(from: outDate!)
            print("24 Hrs Format: \(date24HrsString)")
    
            return outDate
        }