简体   繁体   中英

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

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: :)

You can set the time units into date from the current date-time ie 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", " "));

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')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM