Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

converting JSON time and date format and location format

I'm currently getting a JSON response back with timezone, and date in a utc format. I'd like to switch it to a more readable format. The timezone - "America/Los_Angeles" is a tad bit tricky. Any ideas particularly on how to get to to just show the city? Thank you in advance for any pointers

Plan_it.Start(timezone: "America/Los_Angeles", utc: "2018-06-27T03:00:00Z", local: Optional("2018-06-26T20:00:00"))

When I print these to the console I get the output as so. I would like to get an output like - Basically I need to reformat the output, was my original question.

(May 26, 2018 10:30 and Los Angeles.)

override func viewDidLoad() {
    super.viewDidLoad()

    eventNameLbl.text = detailedEvent?.name.html
    eventStartTimeLbl.text = detailedEvent?.start.local
    eventAddressLbl.text = detailedEvent?.start.timezone
    eventDescriptionLbl.text = detailedEvent?.description.text

output//Optional("2018-05-26T20:30:00")
output//Optional("America/Los_Angeles")

like image 622
Coding while Loading Avatar asked Oct 17 '25 16:10

Coding while Loading


1 Answers

You need to use a DateFormatter. You first need to parse the local string to a Date using the provided timezone. Then you can format that date as desired.

if let dateStr = detailedEvent?.start.local, let timezone = detailedEvent?.start.timezone {
    let formatter = DateFormatter()
    formatter.locale = Locale(identifier: "en_US_POSIX")
    formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
    formatter.timeZone = TimeZone(identifier: timezone)
    if let date = formatter.date(from: dateStr) {
        let df = DateFormatter()
        df.setLocalizedDateFormatFromTemplate("MMMMddyyyyHHmmVVV")
        df.timeZone = TimeZone(identifier: timezone)
        let dateCity = df.string(from: date)
    }
}

Or you can split it out:

if let dateStr = detailedEvent?.start.local, let timezone = detailedEvent?.start.timezone {
    let formatter = DateFormatter()
    formatter.locale = Locale(identifier: "en_US_POSIX")
    formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
    formatter.timeZone = TimeZone(identifier: timezone)
    if let date = formatter.date(from: dateStr) {
       let df = DateFormatter()
       df.dateStyle = .medium
       df.timeStyle = .short
       df.timeZone = TimeZone(identifier: timezone)
       let localdate = df.string(from: date)
       df.dateFormat = "VVV"
       let city = df.string(from: date)
    }
}
like image 95
rmaddy Avatar answered Oct 20 '25 08:10

rmaddy