-1

Has something changed in Swift 5.x? Not sure what I'm doing wrong here.

enter image description here

    extension String {
      var dateValue: Date? {
        let dateAsString = "13:15"
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "HH:mm"
        let date = dateFormatter.date(from: dateAsString) //date is being nil here
        let Date24 = dateFormatter.string(from: date!)
        print("24 hour formatted Date:",Date24)
        return date
       }
    }
rak appdev
  • 717
  • 8
  • 21
  • Is your phone set up in 12h format? Moght need en_us_posix before. – Larme May 24 '20 at 18:49
  • your screenshot and given code aren't same. Which code you are using? – Ankur Lahiry May 24 '20 at 18:52
  • 1
    Your code and your screenshot are not the same. The function`setLocalizedDateFormatFromTemplate` is for converting dates to strings not the other way around. – Fogmeister May 24 '20 at 19:01
  • Updated the question with correct picture and details @Fogmeister and Ankur Lahiry – rak appdev May 24 '20 at 19:53
  • @rakappdev you need to set your DateFormatter locale to "en_US_POSIX" before setting the other properties when parsing a fixed date format. You should set your date formatter calendar as well and if possible its defaultDate. – Leo Dabus May 24 '20 at 21:11

1 Answers1

6

Change your code to :

let dateAsString = "13:15"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "HH:mm"
dateFormatter.timeZone = TimeZone(abbreviation: "GMT+00:00")//Add this
let date = dateFormatter.date(from: dateAsString)
print(date!)

My result is :

2000-01-01 13:15:00 +0000

Hope it helps...

Picode
  • 1,140
  • 1
  • 6
  • 12
  • 1
    I'm still seeing it as nil. Does any of this have to do with the fact that all of this is happening inside an extension? – rak appdev May 24 '20 at 20:20
  • My result is not nil. Are your sure your code same as mine? – Picode May 24 '20 at 20:46
  • Apparently this looks like a bug in Xcode/Swift 5.x as it's not showing nil if I try to print the date object. It is however showing nil when trying to debug by hovering over the variable as shown in the attached picture in Question. – rak appdev May 25 '20 at 04:30