-2

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
2
  • Pretty sure you can't (I'd like to be wrong). You're probably going to need to do most of that you're self, maybe via a localisation workflow so you can better use of placeholder values. I might start with to seperate formatters, one for the start date/time and one for the end time, but that's me Commented Oct 3, 2022 at 1:24
  • what have you tried? What errors did you get? In other words, show a minimal reproducible code that you have tried, see: stackoverflow.com/help/minimal-reproducible-example Commented Oct 3, 2022 at 1:33

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.