0

I followed the example from here, however the year returned is always wrong, like 2000-01-01. Is there a way to simply append to Date() the time I'm passing in? So I have the time as string, this is the func:

// Converts String time (01:07 PM) to Date (2000-01-01 18:07:00 +0000)
    func convertStringTimeToDate(item: String) -> Date {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "hh:mm a"
        dateFormatter.amSymbol = "AM"
        dateFormatter.pmSymbol = "PM"

        let date = dateFormatter.date(from: item)
        
        return date!
    }

For example, time: 01:07 PM would wrongly give me 1 Jan 2000, 01:07 PM. The year has to be correct.

ElKePoN
  • 822
  • 11
  • 21

1 Answers1

-1

This is the solution, thanks @nghiahoang for the help:

// Converts String time (01:07 PM) to Date (2000-01-01 18:07:00 +0000)
    func convertStringTimeToDate(item: String) -> Date {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "hh:mm a"
        dateFormatter.amSymbol = "AM"
        dateFormatter.pmSymbol = "PM"
        dateFormatter.defaultDate = Date()
        
        let date = dateFormatter.date(from: item)
        
        return date!
    }
ElKePoN
  • 822
  • 11
  • 21
  • You need to set your DateFormatter's locale to "en_US_POSIX" otherwise this might crash your app if the device 24h time settings is set to 24 instead of 12 – Leo Dabus Jul 08 '20 at 19:00