2
votes

I have following strings as 12-Hr format time:

let timeFrom = "05:30 AM";
let timeTo = "04:35 PM";

And trying to get date from these for comparison as follows:

let openTime = timeFrom.date(format: "hh:mm a")
let closeTime = timeTo.date(format: "hh:mm a")

With this extension :

extension String
{
    func date(format:String) -> Date?
    {
        let formatter = DateFormatter()
        formatter.dateFormat = format
        formatter.timeZone = NSTimeZone.local
        return formatter .date(from: self)
    }
}

When I print openTime and closeTime, I'm getting incorrect values in time:

print(openTime)      // 2000-01-01 00:00:00 +0000
print(closeTime)     // 2000-01-01 11:00:00 +0000

Why this is so ? I think it is smoething related to time zone, so I visit NSDateFormatter return wrong date + Swift, but nothing worked for me. If anybody have the solution, please help me. Thank you !

1
Find out the difference between "hh" and "HH."El Tomato
oops .. There should be 'hh'. Thanks for pointing out @el Tomato. Checking ...iAkshay
Possible duplicate of Display just the 12 Hour Time format from an ISO 8601 Timestamp and many others.rmaddy
@rmaddy: I've asked string to date for incorrect time. And the duplicate link is about string to string with formatting. You must have look at both questions properly.iAkshay
What are the results that you expect to see?El Tomato

1 Answers

4
votes

I check with swift 3 and Xcode 8 with small changes its working please check

 let timeFrom = "05:30 AM";
 let timeTo = "04:35 PM";
 let openTime = timeFrom.date(format: "hh:mm a")
 let closeTime = timeTo.date(format: "hh:mm a")

 print(openTime)
 print(closeTime)

and make change in extension

extension String{
func date(format:String) -> Date?
{
    let formatter = DateFormatter()
    formatter.timeZone = NSTimeZone(abbreviation: "GMT+0:00") as TimeZone!
    formatter.dateFormat = format
    //formatter.timeZone = NSTimeZone.local
    return formatter .date(from: self)
}}