-7

I am trying to convert the date "01/12/2017" from string to date format but after converting it's giving me this format date 2017-12-01 00:00:00 +0000. But i want date in this format "01/12/2017" only.Here is my code.

  func onlyDate(date: String) -> Date {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "dd/MM/yyyy"
    dateFormatter.timeZone = TimeZone(abbreviation: "GMT+0:00")
    let date1 = dateFormatter.date(from: date)
     print(date1!)
    return date1!
   }
manku
  • 13
  • 1
  • 2
  • 8
  • A date is just a point in time. It has no "format". You need to use DateFormatter to display it as needed. BTW if you want a time insensitive date you should use noon instead and don't set the time zone to gmt. – Leo Dabus Aug 11 '17 at 07:10
  • 1
    Possible duplicate of [Convert string to DATE type in swift 3](https://stackoverflow.com/questions/41435857/convert-string-to-date-type-in-swift-3) – mag_zbc Aug 11 '17 at 07:13
  • I tried the code the from this link also but not getting proper date.It is giving me this result "2017-01-01 00:12:00 +0000". I changed the format to this dateFormatter.dateFormat = "dd/mm/yyyy". – manku Aug 11 '17 at 07:25

2 Answers2

0

Basically, Date class object is not for the formatting. that is only for getting the instance of date, It has its own format.

If you want to format it you can only format it with the string, not to date instance.

Salman Ghumsani
  • 3,647
  • 2
  • 21
  • 34
0

Try this :

let dateFormatters:DateFormatter = DateFormatter()
dateFormatters.dateFormat = "dd/MM/yyyy"
dateFormatters.locale = Locale.current

let date: Date = Date()
print("Current Date : \(date)")
print("Format Date as you want : \(dateFormatters.string(from: date))")

You can use dateFormatters.date(from: yourString) too if you want convert from String into Date

MrX
  • 953
  • 2
  • 16
  • 42