2

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 !

Community
  • 1
  • 1
iAkshay
  • 1,143
  • 1
  • 13
  • 35
  • 4
    Find out the difference between "hh" and "HH." – El Tomato Dec 16 '16 at 06:28
  • oops .. There should be 'hh'. Thanks for pointing out @el Tomato. Checking ... – iAkshay Dec 16 '16 at 06:30
  • Possible duplicate of [Display just the 12 Hour Time format from an ISO 8601 Timestamp](http://stackoverflow.com/questions/15121065/display-just-the-12-hour-time-format-from-an-iso-8601-timestamp) and many others. – rmaddy Dec 16 '16 at 06:37
  • @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 Dec 16 '16 at 07:02
  • What are the results that you expect to see? – El Tomato Dec 16 '16 at 07:15
  • Well, I've just changed timezone as : `formatter.timeZone = NSTimeZone(abbreviation: "GMT") as! TimeZone` and there I got expected time : **2000-01-01 05:30:00 +0000** for 5:30 AM and **2000-01-01 16:30:00 +0000** for 04:30 PM. Thank you for your halp ! @El – iAkshay Dec 16 '16 at 07:19

1 Answers1

4

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 = TimeZone(abbreviation: "GMT+0:00")
    formatter.dateFormat = format
    //formatter.timeZone = TimeZone.current //or autoupdatingCurrent
    return formatter .date(from: self)
}}
Joannes
  • 2,569
  • 3
  • 17
  • 39
Museer Ahamad Ansari
  • 5,414
  • 3
  • 39
  • 45