DateFormatter返回零日期的简单日期字符串 [英] DateFormatter is returning nil date for a simple date string

查看:67
本文介绍了DateFormatter返回零日期的简单日期字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一个问题,即尝试通过DateFromatter将字符串转换为日期的操作只产生了"nil",并且不知道我要去哪里.代码非常简单:

I'm having an issue where an attempt to turn a string into a date via a DateFromatter has produced nothing but 'nil' and I don't know where I'm going wrong. The code is as simple as can be:

    let testDate = "2021"

    let formatter = DateFormatter()
    formatter.locale = Locale(identifier: "en_US_POSIX")
    formatter.dateFormat = "yyyy"

    formatter.timeZone = TimeZone(secondsFromGMT: 0)


    let date = formatter.date(from: testDate)

请注意,这比原先要简单得多,我要格式化的日期实际上是:

Note that this is much simpler than originally, the date I'm trying to format is actually:

"2021-05-01T01:00:00Z"

但是我已经将其剥离下来以缩小问题所在.

But I've stripped it right down to narrow down where the issue is.

从上面可以看到,我已经精简了一年,使用en_US_POSIX配置DateFormatter,并且仅使用"yyyy"作为格式.这可以在Playgrounds中使用,但不能在我的Xcode模拟器(在美国语言环境中)或我自己的物理iPhone(设置为英国语言环境)中使用.话虽这么说,我不知道为什么语言环境会很重要,因为所讨论的字符串只是一年-甚至没有错的年份,也就是零.

As you can see from above, I've stripped down to a year, configured the DateFormatter with en_US_POSIX and used only the 'yyyy' as a format. This works in Playgrounds, but it doesn't work in my Xcode simulator (Which is in the US locale) or my own physical iPhone (set to UK locale). That being said, I've no idea why the locale would matter because the string in question is just a year - it'm not even getting a wrong year, just nil.

我不确定我要去哪里哪里

I'm not sure where I'm going wrong.

推荐答案

Xcode调试器具有错误如您在此帖子中看到的那样,即使解析日期成功,它也会将可选日期显示为nil.如果您打印可选日期,您将看到结果日期.

Xcode Debugger has a bug as you can see in this post that it will show optional dates as nil even when parsing the date succeeds. If you print the optional date you will see the resulting date.

这篇关于DateFormatter返回零日期的简单日期字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆