Search code examples
jsonswiftdate-formattingdateformatter

Date formatting in Swift


I have time values in JSON like so:

             "start_date": "2018-04-20 9:00:00 -08:00",
             "end_date": "2018-4-20 12:00:00 -08:00"

I want to format the dates so that when I put them in a list, I can show for example:

Fri 4/20 9-12 PM

Solution

  • Here's a quick sample on how to do this using date components:

    func toDate(start: String, end: String) -> String {
       let dateFormatter = DateFormatter()
       dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss Z"
       let startDate = dateFormatter.date(from: start)!
       let endDate = dateFormatter.date(from: end)!
    
       let calendar = Calendar.current
       let startComp = calendar.dateComponents([.month,.day,.hour], from: startDate)
       let endComp = calendar.dateComponents([.month,.day,.hour], from: endDate)
       let startMonth = startComp.month!
       let startDay = startComp.day!
       let startHour = startComp.hour!
       let endHour = endComp.hour!
    
       dateFormatter.dateFormat = "a"
       let endTime = dateFormatter.string(from: endDate)
    
       dateFormatter.dateFormat = "E"
       let startDayString = dateFormatter.string(from: startDate)
    
       return "\(startDayString) \(startMonth)/\(startDay) \(startHour)-\(endHour) \(endTime)"
    }
    
    toDate(start: "2018-04-20 09:00:00 -0800", end: "2018-04-20 12:00:00 -0800")
    Output: Fri 4/20 9-12 PM
    

    You should read more on DateFormatter and experiment with it on your own. https://www.zerotoappstore.com/get-year-month-day-from-date-swift.html