I am trying to populate a DateTime field in a mysql table with a value coming from a js script.
So far I have:
let expiredAt = new Date();
expiredAt.setSeconds(expiredAt + process.env.JWT_REFRESH_EXPIRATION);
but it returns
‘Thu Mar 28 2024 04:31:40 GMT+0100 (Ora standard dell’Europa centrale)
that is throwing error in mysql since it is not the correct format. I should be inserting:
2024-03-28 04:31:40
How can I return it? I know there are several similar questions that are focusing on formatting the date on a specific locale. What I want is to convert it to something that is not a locale
2
Answers
You need to fromat the date to return the right format you want, here is an helper function that can do it
here is how to use it:
now you can store the
formatedDate
to the sql db.EDIT:
in order to avoid different locale , and "escape" the locale. you can set the date to be always utc. and use setUTC methods to format the date in a way that it will be always utc. this way you will "avoid" locale, by insuring you always store utc format.
For example you can generate the date with
new Date(Date.UTC(...))
and/or setSeconds withsetUTCSeconds
.also i see you are using it to set seconds to add the expire seconds to the date, im not sure what is the exact use case, but you can think about manipulating the date on the backend, so you will use your server locale, therefore, all the dates will use the same base date, even if converting to utc (or not) . you can check the expire on the backend and be sure its always the same locale..
But basicaly to answer your question about locale, there is no way to avoid locale on js, atleast from what i know. time stamp will be always based on a locale
By the way, this is what mongoDB is doing. i know we are talking about SQL. but just as a reference, mongoDB is converting all dates to be UTC.
You need to convert the
Date
instance into a string and then format it accordingly.One approach is to use JavaScript’s built-in method
toISOString()
. In this example you also need to useslice()
andreplace()
to remove the ‘T’ character from the string (T indicates where the time part of the string begins).