-2

I get from server response in DateTime like this :

2019-04-24T16:25:02.557Z

and I would like only in String:

2019-04-23

How can I do this?

my code:

let dateFormatter = DateFormatter()

dateFormatter.dateFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ssZZZ"

let dateFormatterPrint = DateFormatter()
dateFormatterPrint.dateFormat = "MMM dd,yyyy"
let d = job.postedAt
if let date = dateFormatter.date(from: d) {
    let k = dateFormatterPrint.string(from: date)
    destinationVC.createdJob = k
} else {
    print("There was an error decoding the string")
}
Rob
  • 415,655
  • 72
  • 787
  • 1,044

3 Answers3

0

To convert the 2019-04-24T16:25:02.557Z to a Date object, you'd use:

let iso8601DateFormatter = ISO8601DateFormatter()
iso8601DateFormatter.formatOptions.insert(.withFractionalSeconds)
guard let date = iso8601DateFormatter.date(from: "2019-04-24T16:25:02.557Z") else { return }

And then to output only a date string in the UI, with no time, you'd use something like:

let outputFormatter = DateFormatter()
outputFormatter.dateStyle = .medium
let result = outputFormatter.string(from: date)
Rob
  • 415,655
  • 72
  • 787
  • 1,044
0

What about this ?

func stringFromDate(_ date: Date) -> String {
    let formatter = DateFormatter()
    formatter.dateFormat = "dd MMM yyyy HH:mm" //yyyy
    return formatter.string(from: date)
}
Al-waleed Shihadeh
  • 2,697
  • 2
  • 8
  • 22
-1

Try,

let dateFormatter = DateFormatter()

dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"

let dateFormatterPrint = DateFormatter()
dateFormatterPrint.dateFormat = "yyyy-MM-dd"
let d = "2019-04-24T16:25:02.557Z"
if let date = dateFormatter.date(from: d) {
    let k = dateFormatterPrint.string(from: date)

    print(k)
} else {
    print("There was an error decoding the string")
}

Your dateFormatter.dateFormat should be yyyy-MM-dd'T'HH:mm:ss.SSS'Z' and your dateFormatterPrint.dateFormat should be yyyy-MM-dd.

Subramanian Mariappan
  • 3,736
  • 1
  • 14
  • 29
  • 1
    You don't want quotes around the `Z`, or if you do, you'd have to manually specify the time zone to GMT/UTC/Zulu. It's easiest to remove the quotes around the `Z` in the format string. Also, if you're going to manually create a formatter like this for this ISO8601 string, you must set the local of the first formatter (but not the second one) to `en_US_POSIX`. – Rob Feb 19 '20 at 08:42