17

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 ?

technerd
  • 14,144
  • 10
  • 61
  • 92

2 Answers2

26

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
technerd
  • 14,144
  • 10
  • 61
  • 92
  • 1
    just use `NSTimeZone.local` tor Local, `NSTimeZone.default` for default and `NSTimeZone.system` for system – Leo Dabus Sep 07 '16 at 02:52
  • 2
    @LeoDabus: Yes, we can use `NSTimeZone` directly, but when Xcode automatically convert Swift2.3 code into Swift3.0 then it convert `NSTimeZone` to 'TimeZone'. So it recommends to use Swift Classes. So If any one want to use `TimeZone` then it will cause problem. Thanks! – technerd Sep 07 '16 at 05:13
24

Use this instead of .local in swift 3:

TimeZone.current
RawMean
  • 8,374
  • 6
  • 55
  • 82