Home > Blockchain >  How to get the current time to an existing date in JavaScript?
How to get the current time to an existing date in JavaScript?

Time:12-13

I'm trying to add the current time to an existing date but I'm not sure how to do it. I'm importing stuff into a Postgres database and need a ISO string to update the "updatedAt" column, the imported stuff only has a date like this tho: "2022-03-15", no time.

How would I add the time to this and turn it into a proper ISO string for my database?

const date = new Date('2022-03-15')
const iso = date.toISOSTring() // how to add the current time?
-
Should look like this: "2022-03-15 09:36:54.292613"

Thank you! :)

CodePudding user response:

Try to use dayJs and add the time that you need, https://day.js.org/docs/en/parse/string

dayjs('2018-04-04T16:00:00.000Z')
dayjs('2018-04-13 19:18:17.040 02:00')
dayjs('2018-04-13 19:18')

CodePudding user response:

You can set the time units into date from the current date-time i.e. new Date().

const date = new Date("2022-03-15");
const now = new Date();
date.setHours(now.getHours());
date.setMinutes(now.getMinutes());
date.setSeconds(now.getSeconds());
date.setMilliseconds(now.getMilliseconds());
console.log(date.toISOString());
console.log(date.toISOString().replace("T", " ").replace("Z", " "));

  • Related