简体   繁体   English

我无法将 iso8601 转换为字符串 swift

[英]I can't convert iso8601 to string swift

I have a string coming from API and its format will be like this我有一个来自 API 的字符串,它的格式是这样的

"2021-03-01T15:00:00+07:00" “2021-03-01T15:00:00+07:00”

so i try to convert this string to date using this code所以我尝试使用此代码将此字符串转换为日期

   // string to date
   let dateFormatter = DateFormatter()
   dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"
   let date = dateFormatter.date(from: isoDate)!
   
   print("date from date Formatter = \(date)")
   
   // convert date back to string
   dateFormatter.dateFormat = "EEEE HH:mm"
   let dateString = dateFormatter.string(from: date)
   
   print("date string \(dateString)")
   return dateString    

The result that I expect is -> "2021-03-01 08:00:00 +0000" , "Monday 15:00"我期望的结果是 -> "2021-03-01 08:00:00 +0000" , "Monday 15:00"

When I try this on playground the result is what I want, but when I try this on my project the result is当我在操场上尝试这个结果是我想要的,但是当我在我的项目上尝试这个结果是

-> "1478-03-01 08:00:00 +0000" , "Sunday 14:42" -> "1478-03-01 08:00:00 +0000""Sunday 14:42"

How can I change the result to the same as i expect?如何将结果更改为与我预期的相同? Thanks谢谢

It looks like you are using a different calendar than you expect in your project ( buddhist maybe?) and I guess this is because you haven't set one explicitly so it's the one set in System Preferences.看起来您使用的日历与您在项目中的预期不同(也许是佛教?)我猜这是因为您没有明确设置一个,所以它是系统偏好设置中的一个。

So if you for some reason do not want to use the users current calendar (and locale and time zone) you need to set those properties on your date formatter instance因此,如果您出于某种原因不想使用用户当前的日历(以及区域设置和时区),则需要在日期格式化程序实例上设置这些属性

//Gregorian calendar
dateFormatter.calendar = Calendar.init(identifier: .gregorian)
//UTC time zone
dateFormatter.timeZone = TimeZone(identifier: "UTC")
//English locale
dateFormatter.locale = Locale(identifier: "en_US_POSIX")

This will give you the expected output.这将为您提供预期的 output。

Note that the playground is a bit inconsequent in what it uses and it seems to be a mix of what we have set in our System preferences and hardcoded values.请注意,playground 的使用有点无关紧要,它似乎是我们在系统偏好设置和硬编码值中设置的混合。

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

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