Search code examples
iosswiftswift3nstimezone

Type 'TimeZone' has no member 'local' in Swift3


I am converting project developed in Swift2.3 to Swift3.0 using Xcode8 Beta4. In which I have method to convert date to string, but it fails to convert it.

class func convertDateToString(_ date:Date, dateFormat:String) -> String?
{
    let formatter:DateFormatter = DateFormatter();
    formatter.dateFormat = dateFormat;
    formatter.timeZone = TimeZone.local
    let str = formatter.string(from: date);
    return str;
}

enter image description here

Also in documentation there is no member named local.

Is there any way to use TimeZone directly ? or we have to use NSTimeZone ?


Solution

  • By going deep into class hierarchy,have found NSTimeZone as public typealias, which open up access of NSTimeZone for us.

    Inside TimeZone

    public struct TimeZone : CustomStringConvertible, CustomDebugStringConvertible, Hashable, Equatable, ReferenceConvertible {
    
        public typealias ReferenceType = NSTimeZone
    }
    

    So by using below syntax error get disappear.

    So below code will work.

    For local time zone.

    formatter.timeZone = TimeZone.ReferenceType.local
    

    For default time zone. Use default with same syntax.

    formatter.timeZone =  TimeZone.ReferenceType.default
    

    For system time zone. Use system with same syntax.

    formatter.timeZone = TimeZone.ReferenceType.system
    

    Swift 3

    You can use .current instead of .local.

    TimeZone.current