How to put things in order by time and date?

Hello!

I am working on a schedule from Trello List to Roblox.

This all is working well and GUIs appear.
I just want to make it clearer so GUIs are put in order by time and date.
For example:
Time: Hours (9PM)
Dates: Months and days (October the 21st)

Basically, first order by date and then by time.

How would I do that in script? Like, from trello, first string is date and time, sent like that for example: 2019:09:25:21:00

Thank you

Split the string using string.split and pass a colon as the separator. Use the returned values (it returns a table) to order accordingly. Your method of sorting is up to you; you can use table.sort, if you like.

local timeInfo = string.split("2019:09:25:21:00", ":")

print(timeInfo[1]) -- 2019

If it were up to me, this is something I’d hack together (it’s not a hack though) by removing zeros and ordering by the resultant number.

1 Like

It sounds like you want to sort your objects by Date-Time? If so, I’ve just written the following code for you:

local function sortByDateTime(objs, datetime)
	if not objs or type(objs) ~= "table" then
		return error 'array not passed'
	end
	if not datetime then
		return error 'invalid datetime variable name passed'
	end
	
	local current = os.time()
	local enum    = {
		[1] = "year";
		[2] = "month";
		[3] = "day";
		[4] = "hour";
		[5] = "min";
	}
	
	for _, obj in next, objs do
		local event, count = { }, 1
		for number in obj[datetime]:gmatch("(%d+)") do
			event[enum[count]], count = tostring(number), count + 1
		end
		obj[datetime] = os.time(event)
	end
	
	table.sort(objs, function (a, b)
		return os.difftime(current, a[datetime]) < os.difftime(current, b[datetime])
	end)
	return objs
end

--[!] init
local myObjects = {
	{["time"] = "2015:5:25:21:00", name = "oldest"};
	{["time"] = "2018:5:25:21:00", name = "newest"};
}

--> As you can see above, your date-time variable is called "time"
--> Pass both your array and variable name and it will sort your table from newest to oldest
myObjects = sortByDateTime(myObjects, "time")

table.foreach(myObjects, function (i, v)
	print(i .. ":", "{")
	table.foreach(v, print)
	print("}")
end)

Hope that helps.

1 Like