Dateformatter returns nil date

不问归期 提交于 2019-12-25 03:13:50

问题


I'm trying to add 3 hours to the date I get back from the server. publication.DateTime is a string and I need to first convert it to date before doing the manipulation.

Here's my attempt:

 let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
        dateFormatter.locale = Locale(identifier: "en_US_POSIX")
        let date = dateFormatter.date(from:(publication.DateTime)!) //date is nil here 
        let calendar = Calendar.current
        let components = calendar.dateComponents([.year, .month, .day, .hour], from: date!)
        let finalDate = calendar.date(from:components)

        let newDate = calendar.date(
            byAdding: .hour,
            value: 3,
            to: finalDate!)

What am I doing wrong? I tried to do research online about this issue and it seems like most posts are from an older version of Swift, so maybe there's something in the new Swift I'm missing or doing wrong?

EDIT: Changing the date format worked but adding 3 hours to the time in the string onbject now has the time lookin like e.g. 15:0:0 instead of 12:34:17 it was before. I want it to be 15:34:17.


回答1:


The reason behind not getting minutes and second in your date after adding 3 hours is you have not included those components in components array, please refer below code:

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
dateFormatter.locale = Locale(identifier: "en_US_POSIX")

let date = dateFormatter.date(from:(publication.DateTime)!) 
let calendar = Calendar.current
// Here .minute and .second is added in below line which is missing in your code
let components = calendar.dateComponents([.year, .month, .day, .hour, .minute, .second], from: date!)

let finalDate = calendar.date(from:components)
let newDate = calendar.date(
                byAdding: .hour,
                value: 3,
                to: finalDate!)



回答2:


You just need to change yyyy-MM-dd'T'HH:mm:ssZ to "yyyy-MM-dd'T'HH:mm:ss" and it will work.



来源:https://stackoverflow.com/questions/51325788/dateformatter-returns-nil-date

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!