Home > Back-end >  change the hours on my date object without transforming it in string
change the hours on my date object without transforming it in string

Time:11-17

So I have this date object

const today = new Date()

but it's giving me a time with 3 hours ahead of my timezone how do I change it to my TZ without transforming the final result into a string? My database accepts only date objects not strings I have tried with moment() and localeString() but I need it in date object

CodePudding user response:

You can add to dates by getting the millisecond value, then adding to that, for example:

const today = new Date();
const threeHours = 1000 * 60 * 60 * 3;

const actualTime = new Date(today.getTime()   threeHours);

// just for the demo:
console.log("Original time:", today.toLocaleString());
console.log("Three hours from now:", actualTime.toLocaleString());

CodePudding user response:

You can use the getHours() and setHour() methods and subtract 3.

const today = new Date();
today.setHours(today.getHours() - 3);
console.log(today.toLocaleString());

CodePudding user response:

You're probably looking for Date.prototype.setHours().

Depending on your use case, implementing it is as simple as:

myDateObject = new Date();
console.log(myDateObject.toLocaleString());

myDateObject.setHours(myDateObject.getHours() - 3);
console.log(myDateObject.toLocaleString()); 

  • Related