Best practice showing users local date/time in inertia vue #424
-
Just wondering what everyone is doing to format date/time to users local timzone and format? In a standard laravel app, we have casts and mutators we can use based on users settings. On the vue side we have moment or vue-moment as some good options. I will basically have time based tasks/projects/etc. that will need to be local to the user. I'm not sure which option is better/easier so if anybody has an opinion or insight on this, please share. Thanks for reading |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments
-
You will need to pass all dates and times to your pages in ISO 8601 format, then convert them to moment objects. $model->created_at->format('c'); const createdAt = moment(model.created_at) This gets much more tricky as your users are across different timezones. If you feel more comfortable on the Laravel side, then I would pass all dates and times in the format you already want them to be displayed on the frontend. |
Beta Was this translation helpful? Give feedback.
-
Personally, what I tend to do most of the time, is just use Carbon on the back-end for formatting date/time strings, after which I use them in my front-end directly without mutating them. Something like this: return Inertia::render('Example', [
'createdAgo' => $post->created_at->diffForHumans()
]); However, when I need it to be updated on the front-end reactively depending on (for example) form changes (e.g. extracting the weekday from a selected date string), I do use something like return Inertia::render('Example', [
'createdAt' => $post->created_at->timestamp
]); export default {
props: {
createdAt: String
},
computed: {
weekday() {
return dayjs(this.createdAt).day()
}
}
} If you want to avoid using any third-part JS libraries altogether, you could also use something that I saw @reinink do the other day, which is use the natively supported Intl.DateTimeFormat('en', { dateStyle: 'full' }).formatToParts(Date.parse('2020-01-12 15:22:33'))
// Or, when working with timestamps directly:
Intl.DateTimeFormat('en', { dateStyle: 'full' }).formatToParts(this.createdAt)
Intl.DateTimeFormat('en', { dateStyle: 'full' }).formatToParts(1578838953000) |
Beta Was this translation helpful? Give feedback.
-
Great answers, thank you both for taking the time to respond. I will probably end up handling it mostly on the server side using carbon and mutators, but day.js looks nice also so I may end up using that in some situations. |
Beta Was this translation helpful? Give feedback.
Great answers, thank you both for taking the time to respond. I will probably end up handling it mostly on the server side using carbon and mutators, but day.js looks nice also so I may end up using that in some situations.