如何解析" MongoDB日期时间(ISO日期)"到iOS上的NSDate(快速和客观-c)

时间:2015-06-12 09:19:44

标签: ios mongodb datetime

如何解析" MongoDB日期时间(ISO日期)" iOS上的NSDate(swift and objective-c)

这是json的结果:

{
    "mongodate" : "2015-06-11T14:16:56.643Z"
}

我也回答了这个问题。

3 个答案:

答案 0 :(得分:21)

<强>夫特

  func stringToDate(date:String) -> NSDate {
  let formatter = NSDateFormatter()

  // Format 1
  formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
  if let parsedDate = formatter.dateFromString(date) {
    return parsedDate
  }

  // Format 2
  formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:SSSZ"
  if let parsedDate = formatter.dateFromString(date) {
    return parsedDate
  }

  // Couldn't parsed with any format. Just get the date
  let splitedDate = date.componentsSeparatedByString("T")
  if splitedDate.count > 0 {
    formatter.dateFormat = "yyyy-MM-dd"
    if let parsedDate = formatter.dateFromString(splitedDate[0]) {
      return parsedDate
    }
  }

  // Nothing worked!
  return NSDate().toLocalTime()
}

<强>目标C

NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSSZ"];
NSDate *date = [dateFormat dateFromString:@"2015-06-11T14:16:56.643Z"];

格式:

// Format 1, 12Hour Style
"yyyy-MM-dd'T'HH:mm:ss.SSSZ"
2016-02-12T10:01:31.000+0000
// Format 2, 24Hour Style
"yyyy-MM-dd'T'HH:mm:SSSZ"
2016-02-12T10:01:31Z

答案 1 :(得分:2)

从iOS 10+开始,现在有ISO8601DateFormatter

https://developer.apple.com/reference/foundation/iso8601dateformatter

但是......它没有处理你有时从MongoDB日期字符串中获得的小数秒,这是一个简单的解决方法:

ISO8601DateFormatter doesn't parse ISO date string

答案 2 :(得分:1)

@ fatihyildizhan答案的Swift 3更新:

func stringToDate(date: String) -> Date {
    let formatter = DateFormatter()

    // Format 1
    formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
    if let parsedDate = formatter.date(from: date) {
        return parsedDate
    }

    // Format 2
    formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:SSSZ"
    if let parsedDate = formatter.date(from: date) {
        return parsedDate
    }

    // Couldn't parsed with any format. Just get the date
    let splitedDate = date.components(separatedBy: "T")
    if splitedDate.count > 0 {
        formatter.dateFormat = "yyyy-MM-dd"
        if let parsedDate = formatter.date(from: splitedDate[0]) {
            return parsedDate
        }
    }

    // Nothing worked!
    return Date()
}