 # Sort by date

i am trying to sort by date with entries that are numers,this is what i have,i want to progressivly make older entries farther down the list,is this close?

``````            local nextDay = string.sub(dateTable[k + 1], 0, 2)
local nextMonth = string.sub(dateTable[k + 1], 3, 4)
local nextYear = string.sub(dateTable[k + 1], 5, 6)

if (day < nextDay and month <= nextMonth and year <= nextYear) then
changed = true

local temp = dateTable[k]
dateTable[k] = dateTable[i + 1]
dateTable[i + 1] = temp
end``````

Your string.sub arguments are off. string.sub(text,index,length) and indexes in lua begin at 1 (though 0 is fine for this case).

If you’re stuck with the string date format and want to keep it simple, you may prefer something like
`local month,day,year = date:match("(%d+)/(%d+)/(%d+)")`
(If you can’t guarantee numbers are padded with 0s you’ll want to tonumber them because “3” is greater than “10”.)

If you have a choice in how to store dates and don’t plan to calculate differences but do plan to sort or compare dates, I recommend storing them as YYYYMMDD integers. Then you simply can do:
`table.sort(dateTable,function(e1,e2) return e1>e2 end)`
And it’s easier to compare dates in this format:
`if eventDate >= dateTable[startIndex] and eventDate <= dateTable[endIndex] then -- eventDate is between the two dates`

If you intend to calculate difference between dates, I recommend storing them as timestamps:
`local day1 = time() -- current datetime local day2 = time({month=12,day=25,year=2020}) print("There are",ceil(difftime(day2,day1)/60/60/24),"days between",date("%m/%d/%Y",day1),"and",date("%m/%d/%Y",day2))`
results:
`There are 191 days between 06/17/2020 and 12/25/2020`

See `https://www.wowinterface.com/forums/showthread.php?t=58057#4`