Search code examples
iosswiftnsdateformatterfscalendar

How to get date from static string?


I want to get full date with time like my below code,

func findDate(date: Date)
{
        let format1: DateFormatter = DateFormatter()
        format1.dateFormat = "yyyy-MM-dd"
        let onlyDate = format1.string(from: date) // Here date is like 2019-11-21 

        let dateStr = "\(onlyDate) 10:00 AM"
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd HH:mm a"
        dateFormatter.locale = Locale(identifier: "en_US_POSIX")
        dateFormatter.calendar = NSCalendar.current
        dateFormatter.timeZone = TimeZone.current

        let newDate = dateFormatter.date(from: dateStr)
        print(newDate) // It returns nil

        dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
        let newDateStrInUTC = dateFormatter.string(from: newDate ?? Date()) // Not proper due to newDate = nil
}

In findDate function date argument has date like 2019-11-21 18:30:00 +0000. I want to add my custom time (10:00 AM) in that date.

I received this date (2019-11-21 18:30:00 +0000) from FSCalender.

I want Output like this 2019-11-21 12:00 PM


Solution

  • The problem is with the following line in findDate(date: Date) function.

    dateFormatter.dateFormat = "yyyy-MM-dd HH:mm a"
    

    Replace it to following, and your function should start working as expected.

    dateFormatter.dateFormat = "yyyy-MM-dd hh:mm a"
    

    Explanation:

    HH is used for setting date to 24 Hours format.

    Use small hh, if you wanted to show date in 12 Hours format with AM/PM

    As you are appending 10:00 AM to your onlyDate String. You should use hh:mm a for proper conversion from String to Date.

    Hope it helps.