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.