You mentioned “sorting”… but where is the sort command?
With dateformat(file.ctime, "MMMM") or dateformat(file.ctime, "MM") you’re producing strings, not dates (i.e., you’re grouping by a “produced” string from a date).
Then, by default, groups (as strings) are sorted by alphabetic order!
At the end of each code (the two codes you posted above), add this line