12-Hr格式时间字符串中的日期不正确 - Swift

时间:2016-12-16 06:22:07

标签: swift date time nsdateformatter

我有以下字符串作为12-Hr格式时间:

let timeFrom = "05:30 AM";
let timeTo = "04:35 PM";

并尝试从这些中获取日期以进行比较,如下所示:

let openTime = timeFrom.date(format: "hh:mm a")
let closeTime = timeTo.date(format: "hh:mm a")

使用此扩展程序:

extension String
{
    func date(format:String) -> Date?
    {
        let formatter = DateFormatter()
        formatter.dateFormat = format
        formatter.timeZone = NSTimeZone.local
        return formatter .date(from: self)
    }
}

当我打印openTime和closeTime时,我的时间值不正确:

print(openTime)      // 2000-01-01 00:00:00 +0000
print(closeTime)     // 2000-01-01 11:00:00 +0000

为什么会这样?我认为这与时区有关,所以我访问NSDateFormatter return wrong date + Swift,但没有任何对我有用。如果有人有解决方案,请帮助我。谢谢!

1 个答案:

答案 0 :(得分:4)

我使用swift 3和Xcode 8进行检查,只需更改其工作情况,请检查

 let timeFrom = "05:30 AM";
 let timeTo = "04:35 PM";
 let openTime = timeFrom.date(format: "hh:mm a")
 let closeTime = timeTo.date(format: "hh:mm a")

 print(openTime)
 print(closeTime)

并在扩展名中进行更改

extension String{
func date(format:String) -> Date?
{
    let formatter = DateFormatter()
    formatter.timeZone = NSTimeZone(abbreviation: "GMT+0:00") as TimeZone!
    formatter.dateFormat = format
    //formatter.timeZone = NSTimeZone.local
    return formatter .date(from: self)
}}