在swift中从字符串到日期的转换返回nil [英] Conversion from string to date in swift returns nil

查看:605
本文介绍了在swift中从字符串到日期的转换返回nil的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在swift 3中将字符串转换为日期时遇到问题。这是我的代码,它在转换时返回一个nil值。

I have a problem with converting the string to date in swift 3. Here is my code, it returns me a nil value while converting.

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "EEE, dd MMM yyyy hh:mm:ss +zzzz"
dateFormatter.locale = Locale.init(identifier: "bg_BG")

let recdate = dateFormatter.date(from:"Fri, 10 Mar 2017 15:03:03 +0530")!;`


推荐答案

您为小时和时区设置了错误的格式说明符。使用此:

You set the wrong format specifier for hour and timezone. Use this:

dateFormatter.dateFormat = "EEE, dd MMM yyyy HH:mm:ss Z"
dateFormatter.locale = Locale(identifier: "en_US")




  • hh 表示12小时格式,因此没有小时15.使用 HH 而不是

  • + zzzz 是无效的时区说明符。使用 Z 而不是

  • 除非周五缩短为保加利亚语中的 Fri ,否则请使用英语语言环境

    • hh means 12-hour format so there's no hour 15. Use HH instead
    • +zzzz is invalid timezone specifier. Use Z instead
    • Unless Friday is shortened to Fri in Bulgarian, use an English locale
    • 这篇关于在swift中从字符串到日期的转换返回nil的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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