How to format date?

I tried:
const allPosts = db
.select({
...getTableColumns(posts),
formatted: sql<string>`to_char(created_at, 'Mon DD, YYYY')`,
})
.from(posts);
const allPosts = db
.select({
...getTableColumns(posts),
formatted: sql<string>`to_char(created_at, 'Mon DD, YYYY')`,
})
.from(posts);
but it does not return an array of objects. How do I get an array of objects from the above query? Similar to what this statement returns:
const allPosts = await db.select().from(posts); // returns {title:string...}[]
const allPosts = await db.select().from(posts); // returns {title:string...}[]
7 Replies
Sillvva
Sillvva7mo ago
You might need to cast created_at as a timestamp.
const allPosts = db
.select({
...getTableColumns(posts),
formatted: sql<string>`to_char(`${posts.created_at}::timestamp, 'Mon DD, YYYY')`,
})
.from(posts);
const allPosts = db
.select({
...getTableColumns(posts),
formatted: sql<string>`to_char(`${posts.created_at}::timestamp, 'Mon DD, YYYY')`,
})
.from(posts);
Or use to_date instead
Sillvva
Sillvva7mo ago
PostgreSQL Documentation
9.8. Data Type Formatting Functions
9.8. Data Type Formatting Functions # The PostgreSQL formatting functions provide a powerful set of tools for converting various data types …
textYash
textYash7mo ago
yea but the query still doesn't return an array of objects. It returns this:
No description
textYash
textYash7mo ago
I'm sorry, copying from my editor tooltip isn't working rn
textYash
textYash7mo ago
whereas, a normal query returns simply an array of objects, which is easy to consume.
No description
Sillvva
Sillvva7mo ago
You need to await the query. It is async
textYash
textYash7mo ago
oh silly me It works!! thanks!!! SOLVED
Want results from more Discord servers?
Add your server