Madhur
Madhur

Reputation: 1116

dateFromString() returning wrong date swift 3.0

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

Upvotes: 4

Views: 1570

Answers (3)

Indrajeet
Indrajeet

Reputation: 5666

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.

Upvotes: 11

Kathiresan Murugan
Kathiresan Murugan

Reputation: 2962

 func convertToString(of dateTo: Date) -> String {

        let dateFormatter = DateFormatter()

        dateFormatter.dateFormat = "dd/MM/yyyy" //Your New Date format as per requirement change it own

        let newDate: String = dateFormatter.string(from: dateTo) //pass Date here

        print(newDate) //New formatted Date string

        return newDate
    }

Upvotes: 0

Maulik Bhuptani
Maulik Bhuptani

Reputation: 616

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

Upvotes: 3

Related Questions