learn_swift
learn_swift

Reputation: 83

Unable to get only date from JSON date string in swift

the JSON is like below

"user": {
        "id": 160,
        "date": "2021-04-13 16:30:06",

now i need to show only date in label, if i add like below.. i am getting total string

 self?.dateLabel.text = user?["date"] as? String

o/p: 2021-04-13 16:30:06

i need only 2021-04-13 in self?.dateLabel.text

so i tried

var dateString = user?["date"] as? String
var dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let date = dateFormatter.date(from: dateString!)
 print(date)

o/p: getting nil

how to show only date in label from JSON date string.. please do help

Upvotes: 1

Views: 290

Answers (1)

gcharita
gcharita

Reputation: 8337

You need to use a DateFormatter in order to get the Date object out of the string. To do that you need a date format that matches this string, like this:

var dateString = "2021-04-13 16:30:06"
var dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let date = dateFormatter.date(from: dateString)

After that, you need to modify your DateFormatter with the date format that you want to display:

if let date = date {
    dateFormatter.dateFormat = "yyyy-MM-dd"
    let displayText = dateFormatter.string(from: date)
    print(displayText)
}

Of course, you generally need to know at which timezone this date is represented in the JSON or else you will end up with a wrong date.

To set the time zone in a DateFormatter use timeZone property. For example to set GMT timezone:

dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)

Upvotes: 1

Related Questions