类型'TimeZone'在Swift3中没有成员'local'

tec*_*erd 17 nstimezone ios swift swift3

我正在使用Xcode8 Beta4将Swift2.3中开发的项目转换为Swift3.0.其中我有将日期转换为字符串的方法,但无法转换它.

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;
}
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

同样在文档中没有名为的成员local.

有没有办法TimeZone直接使用?或者我们必须使用NSTimeZone

tec*_*erd 26

通过持续深入的类层次结构,发现NSTimeZonepublic typealias,其开辟的访问NSTimeZone我们.

TimeZone

public struct TimeZone : CustomStringConvertible, CustomDebugStringConvertible, Hashable, Equatable, ReferenceConvertible {

    public typealias ReferenceType = NSTimeZone
}
Run Code Online (Sandbox Code Playgroud)

所以通过使用下面的语法错误得到消失.

所以下面的代码将起作用.

对于当地时区.

formatter.timeZone = TimeZone.ReferenceType.local
Run Code Online (Sandbox Code Playgroud)

对于默认时区.使用default相同的语法.

formatter.timeZone =  TimeZone.ReferenceType.default
Run Code Online (Sandbox Code Playgroud)

对于系统时区.使用system相同的语法.

formatter.timeZone = TimeZone.ReferenceType.system
Run Code Online (Sandbox Code Playgroud)

斯威夫特3

你可以用.current而不是.local.

TimeZone.current
Run Code Online (Sandbox Code Playgroud)

  • @LeoDabus:是的,我们可以直接使用`NSTimeZone`,但是当Xcode自动将Swift2.3代码转换为Swift3.0时,它会将`NSTimeZone`转换为'TimeZone'.所以它建议使用Swift类.因此,如果任何人想使用`TimeZone`那么它将导致问题.谢谢! (2认同)

Raw*_*ean 24

使用此而不是.local在swift 3中:

TimeZone.current
Run Code Online (Sandbox Code Playgroud)

  • 这应该是正确答案:) (2认同)