2016-09-06 14 views
14

我使用Xcode8 Beta4将Swift2.3中开发的项目转换为Swift3.0。其中我有方法将日期转换为字符串,但它无法将其转换。类型'TimeZone'在Swift3中没有成员'local'

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

此外,在文件没有名为local成员。

有什么办法可以直接使用TimeZone?或者我们必须使用NSTimeZone

+0

试试这个formatter.timeZone =。本地 –

+0

'NSTimeZone.local'的作品,同为'.system'和'.default'。您可以在Apple提交错误报告。 –

+0

@ Anbu.Karthik:'.local'也不起作用。 – technerd

回答

23

通过深入课堂层次结构,发现NSTimeZonepublic typealias,这为我们打开了NSTimeZone的访问权限。

TimeZone

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

    public typealias ReferenceType = NSTimeZone 
} 

因此,通过使用下面的语法错误得到消失。

所以下面的代码将工作。对于本地时区。

formatter.timeZone = TimeZone.ReferenceType.local 

对于默认时区。 使用default具有相同的语法。

formatter.timeZone = TimeZone.ReferenceType.default 

对于系统时区。 使用system具有相同的语法。

formatter.timeZone = TimeZone.ReferenceType.system 

斯威夫特3

可以使用.current而不是.local

TimeZone.current 
+1

只使用'NSTimeZone.local'本地,'NSTimeZone.default'为默认值,'NSTimeZone.system'为系统 –

+2

@LeoDabus:是的,我们可以直接使用'NSTimeZone',但是当Xcode自动将Swift2.3代码转换成Swift3.0然后它将'NSTimeZone'转换为'TimeZone'。所以它建议使用Swift类。所以如果有人想使用'TimeZone',那么它会导致问题。谢谢! – technerd

22

使用此而不是在SWIFT 3 .local

TimeZone.current 
+2

这应该是正确的答案:) – dustinrwh

相关问题