0

I have a list of UNIX timestamps which I convert into dates using DateFormatter. The array I have after formatting is something like this:

04-19-2017 04:50

04-19-2017 07:50

04-20-2017 14:31

04-20-2017 16:55

04-20-2017 21:08

04-21-2017 01:25

04-22-2017 05:34

I want to do this in order a table of dates without showing the same day twice, like: day - hour, hour, hour, instead of day - hour, day - hour, day - hour. Should I use dictionary to do it? Are you familiar with an easy way to do this? Thanks!

Paul John
  • 115
  • 8

1 Answers1

0

I don't think that's possible because the date format will get disturbed because of that and then you can't get it back to the proper date format.

But if you want a dictionary format, you could use this code:

func getDatesToDictionary(dates: [Date]) -> [String: Any] {

        let dateFormatterOne = DateFormatter()
        dateFormatterOne.dateFormat = "MM-dd-YYYY HH:mm"
        let dateFormatterTwo = DateFormatter()
        dateFormatterTwo.dateFormat = "MM-dd-YYYY"

        let fullDate = dateFormatterOne.string(from: dates[0])
        let fullDateTemp = dateFormatterTwo.date(from: fullDate)
        let finalDateString = dateFormatterTwo.string(from: fullDateTemp!)

        var dateDictionary: [String: Any] = [:]
        var dateArray: [Date] = []

        let dateFormatterThree = DateFormatter()
        dateFormatterThree.dateFormat = "HH:mm"

        for eachDate in dates {

            let fullDateHour = dateFormatterOne.string(from: eachDate)
            let finalDateHourString = dateFormatterThree.date(from: fullDateHour)
            dateArray.append(finalDateHourString!)
        }

        dateDictionary = [finalDateString: dateArray]
        return dateDictionary
    }
CoderSulemani
  • 123
  • 11