daniel8x
daniel8x

Reputation: 1080

Weird format Date to `toLocaleString` in javascript

I have an app that is currently running in Production. Suddenly, I have experienced a weird issue that I am not able to figure it out to prevent it. Any suggestion is highly appreciate.

This is the function where the error happened:

date_time: new Date(
                this.selectedDate.getFullYear(),
                this.selectedDate.getMonth(),
                this.selectedDate.getDate(),
                this.selectedHour.value.split(':')[0],
                this.selectedHour.value.split(':')[1],
                0
              ).toLocaleString(),

This date_time will be saved in database. Output Example: 12/9/2021, 2:00:00 PM. Everything is working as expected. However, today there is new record in database with different format: 12/9/2021 2:00:00 p.m. And it messed up my app. Do you know what happen to toLocaleString() ? Thank you.

Upvotes: 1

Views: 480

Answers (1)

Quentin
Quentin

Reputation: 943586

Since you tagged this I assume this code is running client-side and sending the resulting string to the server for insertion into your database.

toLocaleString converts a date to a string formatted for the user's locale.

It is designed to display a human readable date.

If a user with their system set to a different locale (likely because they are from a different country to you) then it will give different results.

If you want a standard date in a format that is easily machine processable (i.e. good for storing in a database) then use toISOString.

You can parse it and convert it to a local string for display later.

Upvotes: 1

Related Questions