简体   繁体   English

Swift - iOS - 将字符串转换为日期并发出

[英]Swift - iOS - Convert String to Date & issue

I have an extension on String to convert my date strings to a Date type in Swift 5.2我在 String 上有一个扩展,可以将我的日期字符串转换为 Swift 5.2 中的日期类型

extension String {
  func toDate(withFormat format: String = "MMM d, YYYY HH:mm:ss a") -> Date {
    let dateFormatter = DateFormatter()
    dateFormatter.locale = Locale(identifier: "en_US")
    dateFormatter.calendar = Calendar(identifier:  .iso8601)
    dateFormatter.timeZone = .current
    dateFormatter.dateFormat = format
    guard let date = dateFormatter.date(from: self) else {
      preconditionFailure("Check the format!!!")
    }
    return date
  }
}

when I try this to convert my date_string is always wrong(check below) :当我尝试用这个来转换我的 date_string 时总是错误的(检查下面):

var sampleDate = "May 5, 2021 1:34:15 AM"
let newDate = sampleDate.toDate()
print(newDate) //prints: "2020-12-28 05:34:15 +0000\n"

My date_string that I want to convert is always in a similar format: "May 5, 2020 9:20 5:39:15 PM"我要转换的 date_string 始终采用类似的格式:“2020 年 5 月 5 日 9:20 5:39:15 PM”

Any idea what could be wrong?知道有什么问题吗? I played around with local, calendar, timezone but did not work!我玩过本地,日历,时区,但没有用! I'm in the US East Coast timezone right now.我现在在美国东海岸时区。

Thanks, Cam谢谢,卡姆

Your DateFormatter's dateFormat should be "MMM d, yyyy hh:mm:ss a"你的 DateFormatter 的 dateFormat 应该是"MMM d, yyyy hh:mm:ss a"

("yyyy" instead of "YYYY" and "hh" instead of "HH") (“yyyy”代替“YYYY”和“hh”代替“HH”)

That works.这样可行。

Edit:编辑:

Or, as Leo pointed out in the comments, "MMM d, yyyy h:mm:ss a" (With only one h ) would be better, and it's safer to use或者,正如 Leo 在评论中指出的那样, "MMM d, yyyy h:mm:ss a" (只有一个h )会更好,而且使用起来更安全

dateFormatter.locale = Locale(identifier: "en_US_POSIX")

(That tells the date formatter not to try to adjust the date format for different local date formatting conventions.) (这告诉日期格式化程序不要尝试为不同的本地日期格式约定调整日期格式。)

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

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