#How to sort a content collection by date?
1 messages · Page 1 of 1 (latest)
This worked:
allPosts.sort((a, b) => {
const pubDateA = new Date(a.data.pubDate);
const pubDateB: Date = new Date(b.data.pubDate);
return pubDateB.getTime() - pubDateA.getTime();
});
if you use content collection, you can easily cast dates with zod using: z.date().default(() => new Date())
then you can simplify your code since you'll have guarantee that pubDate is an instance of Date such as:
allPosts.sort(({ data: a }, { data: b }) => b.pubDate - a.pubDate);
I don't think this is reliable
This will give the exact datetime of runtime when a post has missing date.
if pubDate is missing, previous algorithm would resolve as new Date(undefined) which is an invalid date and would break the sorting
best would be not to set default and force error from content schema, but it's also kinda annoying bc when you just start creating a content file, the schema gets evaluated as soon as you create the file. so having default would prevent an early round of error