当使用DateFormatter()。date(from:String)时,Date Formatter返回

时间:2019-09-22 12:28:26

标签: swift nsdateformatter ios13 dateformatter

我有以下代码:

//converting date into desired format
    let formatterGet = DateFormatter()
    formatterGet.dateFormat = "yyyy-MM-dd HH:mm:ss zzzz" //"2014-09-21 21:00:00  0000"
    let date = formatterGet.date(from: birthday) 
    print(date)

    // "decoding" the new format to be shown in the UI
    let formatterShow = DateFormatter()
    formatterShow.dateFormat = "MMM dd, yyyy"
    birthdayTextField.text = formatterShow.string(from: date ?? Date())

问题是当我在控制台中打印日期时,每次都显示nil。我该如何解决?

1 个答案:

答案 0 :(得分:1)

问题是您的DateFormatter转换。您有两种选择:

1:从格式化程序和日期中删除zzzz

    let birthday = "2014-09-21 21:00:00"
    let formatterGet = DateFormatter()
    formatterGet.dateFormat = "yyyy-MM-dd HH:mm:ss"
    let date = formatterGet.date(from: birthday)

    print(date)

输出:

    Optional(2014-09-22 00:00:00 +0000)

2:在日期上添加+符号:

   let birthday = "2014-09-21 21:00:00 +0000"
   let formatterGet = DateFormatter()
   formatterGet.dateFormat = "yyyy-MM-dd HH:mm:ss zzzz"
   let date = formatterGet.date(from: birthday)

   print(date)

输出:

   Optional(2014-09-22 00:00:00 +0000)