简体   繁体   English

在swift中从字符串到日期的转换返回nil

[英]Conversion from string to date in swift returns 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.我在 swift 3 中将字符串转换为日期时遇到问题。这是我的代码,它在转换时返回一个 nil 值。

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 means 12-hour format so there's no hour 15. Use HH instead hh表示 12 小时制,因此没有 15 小时。请改用HH
  • +zzzz is invalid timezone specifier. +zzzz是无效的时区说明符。 Use Z instead使用Z代替
  • Unless Friday is shortened to Fri in Bulgarian, use an English locale除非在保加利亚语中星期五缩短为Fri ,否则请使用英语语言环境

You have a couple of problems, first, as pointed out by Code Different, you need to be using HH to read 24-hour times.您有几个问题,首先,正如 Code Different 所指出的,您需要使用 HH 来读取 24 小时制时间。 But, you're also specifying a locale, which means that the "word" portions must be in bulgarian, not english.但是,您还指定了语言环境,这意味着“单词”部分必须是保加利亚语,而不是英语。 Leaving the language the default seems to work fine:离开默认语言似乎工作正常:

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")!

If you were to use Bulgarian day and month names, your format should work.如果您要使用保加利亚的日期和月份名称,您的格式应该可以工作。

dateFormatter.date(from:"нд, 10 март 2017 15:03:03 +0530")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM