Formatting Dates
Answered
Blue Picardy Spaniel posted this in #help-forum
Blue Picardy SpanielOP
How do I format a date based on the user's locale? For example, Americans do it MM/DD but brits do it DD/MM.
Answered by Blue Picardy Spaniel
i disabled ssr and moved the columns to the table component directly
29 Replies
Blue Picardy SpanielOP
but how do i get their locale to know what to select
This is one way of doing it. You can customize the dates more than just the the locale way of doing it using the
options object in the exampleCheck to see if Accept-Language is being set
In the header
Blue Picardy SpanielOP
how do i get the header
I'll try to find a better way which works across all browsers but surely there would be a library out there
If im correct the normal way of localizing is by adding i8ln to your site. When the user changes sites, you can change the locale appropriately
Blue Picardy SpanielOP
im not sure why it's so difficult to format a date
Thats just how it is. Number and dates both can be a headache to deal with
Blue Picardy SpanielOP
surely someone has done this before
Btw try passing nothing/undefined to
toLocaleDateString()Maybe that is all you need
If it doesnt work you can try your hand on : https://developer.mozilla.org/en-US/docs/Web/API/Navigator/languages
@Clown Btw try passing nothing/undefined to `toLocaleDateString()`
Blue Picardy SpanielOP
im getting an error for some reason when i do this:
Text content did not match. Server: "28/04/2024, 15:31:11" Client: "4/28/2024, 3:31:11 PM"Ah yes, time dependent stuff cause hydration errors
You can try one of the solutions below
Blue Picardy SpanielOP
alright
Blue Picardy SpanielOP
@Clown i have an issue
here's my file:
const TableColumns: ColumnDef<GlobalBan>[] = [
{
accessorKey: "reason",
header: "Ban Reason"
},
{
accessorKey: "date",
header: "Date",
cell: ({ row }) => {
const date = row.original.date;
if(!date) return "Unknown";
return date.toLocaleString();
}
}
];
export default TableColumns;that's it
it's not a react component or anything
so i cant use hooks, useEffect, etc
maybe a simple
return <span suppressHydrationWarning>{date.toLocaleString()}</span>Blue Picardy SpanielOP
i managed to fix it, took a while tho
Blue Picardy SpanielOP
i disabled ssr and moved the columns to the table component directly
Answer