0

I need to add the current time to a date, but there is no way to do it

const d = new Date();
const time = {
  seconds: d.getSeconds(),
  minuts: d.getMinutes(),
  hours: d.getHours(),
  mills: d.getMilliseconds()
}

const dd = new Date("2022-11-21");
let newDate = `${dd}T${time.hours}:${time.minuts}:${time.seconds}.${time.mills}Z`
let ff = new Date(newDate)
console.log(d.toISOString());
console.log(ff.getUTCDate());

2
  • The way you use dd makes no sense. When using it in a template literal, you’re coercing the Date object to a string, but String(new Date("2022-11-21")) is a localized string of the full date; however, for whatever reason, you assume that it’s part of an ISO 8601 string. Why? Read the documentation. You probably meant ${dd.toISOString().split("T")[0]}. Commented Nov 23, 2022 at 20:49
  • 1
    The Date object has a bunch of constructor overloads that you can use to pass each part of the date in individually. You probably want something like new Date(dd.getYear(), dd.getMonth(), dd.getDay(), time.hours, time.minuts, time.seconds, time.mills). Commented Nov 23, 2022 at 20:53

1 Answer 1

1

If you want the current time to a past date, you should just grab the time from d and stick it on dd

const d = new Date();

const dd = new Date("2022-11-21");
dd.setSeconds(d.getSeconds())
dd.setMinutes(d.getMinutes())
dd.setHours(d.getHours())
dd.setMilliseconds(d.getMilliseconds())

console.log(dd)

Sign up to request clarification or add additional context in comments.

6 Comments

When I downvoted you didn't have a code example in your answer, it was just an extremely vague description. Next time add an example before you post the answer.
yeah sorry ... i posted a shorter version now .. you were creating a useless pivot object
Does it work for you? I would appreciate an upvote ahaha I am missing 7 points reputation to write comments ... actually I wanted to comment on your post, but I am not yet allowed! please help me ehehe
@Jesse ohh sorry, I thought you were the creator of the post ... I am still new on here .. even tho i subscribed one year and half ago!
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.