mdkamrul
mdkamrul

Reputation: 274

Nodejs change time at date type after getting from Mongodb

I wanted to change time at date type which returning from mongodb with custom time like below

"2021-05-26T00:00:00.000Z"

to

"2021-05-26T10:20:00.000Z"

I wanted to change time from a variable at the date, so my technique was split this date with "T" then get time part and change it with custom time

let splitedTime = timev[0].validFrom.toString().split()[0];
let customTime = "10:20:00.000Z";
let finalTime = splitedTime + customTime;

but this split not working this giving me date like this "Wed May 26 2021 06:00:00 GM". Can you please help me for this?

Upvotes: 0

Views: 808

Answers (1)

Isolated
Isolated

Reputation: 2453

Working with Date

Whilst I understand your logic of converting it to a string and then using string methods to convert it to your desired output, I believe a simpler approach is to use the Date object


function dateAdd(original, hours, minutes) {
  const date = new Date(original);

  date.setHours(original.getHours() + hours);
  date.setMinutes(original.getMinutes() + minutes);

  return date.toISOString();
}

When original = "2021-05-26T00:00:00.000Z" then the return value is "2021-05-26T10:20:00.000Z".

If you want a fixed time:


const date = new Date('2021-05-26T00:00:00.000Z');

date.setUTCHours(10);
date.setUTCMinutes(20);
date.setUTCSeconds(0);
date.setUTCMilliseconds(0);

// a cleaner approach:
date.setUTCHours(10, 20, 0); // hoursValue, minutesValue, secondsValue

console.log(date.toISOString());

Which produces the following:


"2021-05-26T10:20:00.000Z"

Another Solution

Your actual problem is being caused by the fact you call toString which returns a date string in the format of "Tue Aug 19 1975 23:15:30 GMT+0200 (CEST)" so when you're splitting by "T", that's way down at the end. toISOString will return the correct format.

Explanation

As you can see above, we avoid using string methods and use the methods that exist on Date. This approach is safer as you avoid issues with the difference between toISOString and toString. You may also find moment useful if you're using dynamic methods of changing dates regularly.

Note

In all honesty, I'm not entirely sure I understand the why behind what you're doing, so if I'm wrong please correct me so I can update my answer to be more relevant for you.

Learn More

  1. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toString
  2. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString
  3. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

Upvotes: 1

Related Questions