0

Here , I want to convert the UTC time to Local time formate in swift 3, but i'am not able to convert it. Please help me for this

let StrDate = "2018-03-06T13:32:57 +05:30" I want to Convert this Date into local time format.

 func convertStringDateFormateUTC(strDate: String,
     strCurrentFormateType:String, strFormateType:String) -> String {
            let dateFormatter = DateFormatter()
            dateFormatter.dateFormat = strCurrentFormateType
            var strNewdate = NSDate()
            strNewdate = dateFormatter.date(from: strDate)! as NSDate
            dateFormatter.dateFormat = strFormateType;
            dateFormatter.timeZone = TimeZone.init(abbreviation: "UTC")
            return dateFormatter.string(from: strNewdate as Date)
        }
Kaushik Makwana
  • 1,329
  • 2
  • 14
  • 24
jo solution
  • 401
  • 5
  • 18
  • 2
    Possible duplicate of [Swift 3.0 : Convert server UTC time to local time and visa-versa](https://stackoverflow.com/questions/42803349/swift-3-0-convert-server-utc-time-to-local-time-and-visa-versa) – CodeChanger Mar 07 '18 at 04:54

1 Answers1

0

Use TimeZone.current to detect local timezone and apply it.

let formatter = DateFormatter()
// initially set the format based on your datepicker date
var localTimeZoneAbbreviation: String { return TimeZone.current.abbreviation() ?? "UTC" }
//print(localTimeZoneAbbreviation)
formatter.locale = Locale.init(identifier: localTimeZoneAbbreviation)
// convert your string to date
let yourDate = formatter.date(from: strDate)
//then again set the date format which type of output you need

In your function :

func convertStringDateFormateUTC(strDate: String,
                                 strCurrentFormateType:String, strFormateType:String) -> String {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = strCurrentFormateType

    var localTimeZoneAbbreviation: String { return TimeZone.current.abbreviation() ?? "UTC" }
    dateFormatter.locale = Locale.init(identifier: localTimeZoneAbbreviation)

    var strNewdate = NSDate()
    strNewdate = dateFormatter.date(from: strDate)! as NSDate
    dateFormatter.dateFormat = strFormateType;
    dateFormatter.timeZone = TimeZone.init(abbreviation: "UTC")
    return dateFormatter.string(from: strNewdate as Date)
}
Sid Mhatre
  • 3,272
  • 1
  • 19
  • 38