-1

I am trying to show some date value as a label text in swift 3, but getting type conversion error. Here is my code.

let dateString = "2016-12-15T22:10:00Z"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy/MM/dd"
let s = dateFormatter.date(from: dateString)

lblDate.text = s

I am getting this error

Cannot assign value of type date to type string

Any help!

vadian
  • 274,689
  • 30
  • 353
  • 361
h_h
  • 1,201
  • 4
  • 28
  • 47

1 Answers1

1

You have two problems.

  1. You are trying to assign a Date to a String.
  2. You have the wrong format for your string.

This fixes both problems:

let dateString = "2016-12-15T22:10:00Z"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
let date = dateFormatter.date(from: dateString)
dateFormatter.dateFormat = "yyyy/MM/dd"
let s = dateFormatter.string(from: date)

lblDate.text = s

This changes the string from 2016-12-15T22:10:00Z to 2016/12/16.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
  • No, The format I used here is just a sample, i am getting dates like this 2016-12-15T22:10:00Z which i really need to format – h_h Dec 16 '16 at 17:27
  • 1
    Then please update your question with your real issue instead of wasting people's time with misleading questions. – rmaddy Dec 16 '16 at 17:27
  • try `"yyyy-MM-dd'T'HH:mm:ssZ"` using this answer http://stackoverflow.com/questions/28016578/swift-how-to-create-a-date-time-stamp-and-format-as-iso-8601-rfc-3339-utc-tim/28016692#28016692 – Leo Dabus Dec 16 '16 at 17:33
  • @h_a86 I updated my answer to reflect your updated question. – rmaddy Dec 16 '16 at 17:35