Dateformatter returns nil date

2019-08-27 11:47发布

问题:

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.