【问题标题】:Convert this date string to NSDate "2016-09-23T23:06:00+00:00"将此日期字符串转换为 NSDate "2016-09-23T23:06:00+00:00"
【发布时间】:2015-09-25 20:53:55
【问题描述】:

我试图将此字符串转换为 NSDate, 它适用于美国位置,但是当我改为巴西时。 Bumm,它崩溃了! 我应该使用哪种格式字符串?

这是我的代码:

static func textToDatedateString: String) -> NSDate {
    let dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss+00:00"
    let date = dateFormatter.dateFromString(dateString)!

    return date
}

【问题讨论】:

  • 提供有关崩溃的详细信息。
  • 它返回 nil,并因“无法包装 nil 值”而崩溃
  • 将日期格式化程序的区域设置为en_US_POSIX
  • 男人!你真棒! THX

标签: ios string swift date nsdate


【解决方案1】:

您忽略了字符串中的时区信息。这样,您输入的时间实际上是 UTC +00:00 的当地时间。此外,您还强制解开您的字符串,如果您输入无效的字符串日期,它会使您的应用程序崩溃。试试这样:

func textToDate(dateString: String) -> NSDate? {
    let dateFormatter = NSDateFormatter()
    dateFormatter.calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierISO8601)!
    dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssxxx"
    dateFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
    return dateFormatter.dateFromString(dateString)
}

if let dateFromString = textToDate("2016-09-23T23:06:00+00:00") {
    print(dateFromString)   // "2016-09-23 23:06:00 +0000"
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-12-17
    • 2017-01-27
    • 2011-05-09
    • 1970-01-01
    • 2021-03-30
    • 1970-01-01
    • 2018-03-23
    • 1970-01-01
    相关资源
    最近更新 更多