Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Convert NSDate from local timezone to UTC and vice versa in Swift 3.0

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 6.31k
    Comment on it

    1. To convert UTC(Coordinated Universal Time) to Local timezone

    func convertToLocalDateFromUTCDate(dateStr : String) -> String {
            let formatter = DateFormatter()
            formatter.dateFormat = "yyyy-MM-dd HH:mm:ss Z"
            let sourceDate = formatter.date(from: dateStr)
            let formatter2 = DateFormatter()
            formatter2.dateFormat = "MMM dd @hh:mm aa"
            let localTime = formatter2.string(from: sourceDate!)
            print("local time %@",localTime)
            return localTime
        }
    

    2.To convert Local timezone to UTC(Coordinated Universal Time)

    func convertToUTCFromLocalDate(dateStr : String) -> String {
            let formatter = DateFormatter()
            formatter.dateFormat = "MMM dd @hh:mm aa"
            let utc = NSTimeZone(abbreviation: "UTC")
            formatter.timeZone = utc as TimeZone!
            formatter.dateFormat = "MMM dd @hh:mm aa"
            let localDate: Date? = formatter.date(from: dateStr)
            let timeZoneOffset: TimeInterval = TimeInterval(NSTimeZone.default.secondsFromGMT())
            let utcTimeInterval: TimeInterval? = (localDate?.timeIntervalSinceReferenceDate)! - timeZoneOffset
            let utcCurrentDate = Date(timeIntervalSinceReferenceDate: utcTimeInterval!)
            print(UTC time %@",utcCurrentDate)
            return formatter.string(from: utcCurrentDate)
        }
    

     

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: