【问题标题】:Swift language bug in DateFormatter? [duplicate]DateFormatter 中的 Swift 语言错误? [复制]
【发布时间】:2017-09-22 17:39:58
【问题描述】:

我正在测试一个具有 UITextField 的应用程序,用户可以在其中输入日期,因此我采用输入的字符串并使用 DateFormatter 生成 Date 对象。

当我尝试转换返回 nil 值的字符串“10/15/2017”时,第一次出现问题。所以我创建了一个代码来生成从“01/01/2000”到“12/31/2020”的字符串,我意识到这个问题在每年的 10 月或 11 月左右都会发生。 我创建了一个代码来打印所有返回 nil 值的日期:

import UIKit
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .short
dateFormatter.locale = Locale(identifier: "en_US")

for day in 1...30 { // Generate the days
    for month in 1...12 { // Generate the months
        for year in 2000...2020 {
            if month == 2, day > 28 { // Check if month is february
               continue
            }
            str = "\(String(format: "%02d", month))/\(String(format: "%02d", day))/\(String(format: "%02d", year))"
            let date = dateFormatter.date(from: str)          
            if date == nil {
                print("\(str)")
            }
        }
    }
}

我还尝试更改 dateFormat,甚至是 locale 属性,但某些条目的结果也为零。

dateFormatter.dateFormat = "MM/dd/yyyy"

这段代码的 sn-p 打印出以下内容:

11/02/2004
11/03/2002
11/05/2006
10/08/2000
10/14/2001
10/14/2007
10/15/2017
10/16/2005
10/16/2011
10/16/2016
10/17/2010
10/18/2009
10/18/2015
10/18/2020
10/19/2003
10/19/2008
10/19/2014
10/20/2013
10/20/2019
10/21/2012
10/21/2018

我正在使用 Xcode 8.3.3 和 Swift 3。这是 Swift/Xcode 的错误还是我做错了什么?

【问题讨论】:

  • 我无法复制它。 – 但是您应该使用固定的dateFormatter.dateFormat(在您的情况下:“MM/dd/yyyy”)用于解析日期。
  • @MartinR 我尝试将dateFormatter.dateFormat 与“MM/dd/yyyy”和“dd/MM/yyyy”一起使用,但我得到了相同的结果。
  • 你的时区是什么?
  • 我的时区是“美国/圣保罗”(UTC -3)
  • @LeoDabus - 酷。这是一个有趣的解决方法。如果日期格式化程序的calendar 是“未指定”,则“使用当前用户的逻辑日历”。我讨厌编写依赖于这个未记录的“功能”的代码,如果你用当前日历替换当前用户的逻辑日历,行为就会改变。

标签: swift dateformatter


【解决方案1】:

这很可能是巴西秋季综合症

巴西的夏令时变化发生在午夜。在秋季,当时钟拨快时,没有 12:00 am / 0:00 所以日期是nil

将时区设置为在午夜不发生夏令时更改的国家/地区或将小时设置为中午

【讨论】:

  • 他只需要设置 Date Formatter 日历。无需更改时区
猜你喜欢
  • 1970-01-01
  • 2018-10-13
  • 1970-01-01
  • 2018-02-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多