Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dateFromString() returning wrong date swift 3.0

Tags:

ios

swift3

i am passing "01/12/2017" in the fromDate.text(textfield), but receiving unexpected output.

      let formatter = DateFormatter.init()
      formatter.dateFormat = "dd/mm/yyyy"
      startDate = formatter.date(from: fromDate.text!)
      print("startDate = \(startDate)")

output is : 31/12/2016

like image 649
Madhur Avatar asked Dec 08 '22 16:12

Madhur


2 Answers

The format of date should be dd/MM/yyyy not dd/mm/yyyy. The mm indicates the minutes and MM indicates the month.

And also add the below line in your code

formatter.timeZone = TimeZone(abbreviation: "GMT+0:00")

This line of code set time zone. If you not, then you get 30/11/2017 in output.

The reason behind this is when string date not contain time then formatter assume that it is midnight and you also not given the timezone so it will take current timezone.

like image 56
Indrajeet Avatar answered Dec 11 '22 09:12

Indrajeet


It has to be dd/MM/yyyy dateformat. MM in capital.

like image 28
Maulik Bhuptani Avatar answered Dec 11 '22 10:12

Maulik Bhuptani