-3

In the database the timetable comes in the right format

2022-04-26T08:15:08.000Z

When I use node to select, the time is

2022-04-26T11:15:08.000Z

On the front end I tried

hours.setHours(hours.getHours() - 3);

but it did not work, Show me this

horas.getHours is not a function

I need to change the time from

"2022-04-26T11:15:08.000Z"

to

 "2022-04-26T08:15:08.000Z",

If possible to create a function that removes 3 hours, it would be better

Juan
  • 57
  • 1
  • 5
  • 1
    Something like that should work. Can you show us more of the code. – phuzi Apr 26 '22 at 11:38
  • 1
    "but it did not work" - how did it not work? (Did you allow for the fact that the console will translate the date to your machine's time zone?) – mbojko Apr 26 '22 at 11:39
  • I will edit my question @phuzi – Juan Apr 26 '22 at 11:44
  • 1
    `let now = new Date(); console.log(now); now.setHours(now.getHours() - 3); console.log(now);` shows the time changes to 3 hours before. Something about the "hours" variable may be incorrect. – Peter Krebs Apr 26 '22 at 11:44
  • Does this answer your question? [How to add hours to a Date object?](https://stackoverflow.com/questions/1050720/how-to-add-hours-to-a-date-object) – ashishmishra Apr 26 '22 at 11:47
  • 1
    Looks like you need to parse the ISO 8601 formatted string in to an actual Date object first. – phuzi Apr 26 '22 at 11:50
  • Could you show me how to do this? – Juan Apr 26 '22 at 11:54
  • Why not take a look at [the documentation for Date](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) – phuzi Apr 26 '22 at 11:55
  • my solution at the moment is "function FornatarHoras(horas) { let hours = horas.substring(11,13) let diminuirHoras = hours - 3; let minutes = horas.substring(14,16) let dateFormated = `${diminuirHoras}:${minutes}` return dateFormated }", but but i don't think this is correct – Juan Apr 26 '22 at 11:56
  • Maybe you should also wonder why there's a 3 hours difference between frontend and backed. Maybe timezone? Manual manipulations on timezones may be dangerous – Christian Vincenzo Traina Apr 26 '22 at 13:34

3 Answers3

0

You can convert your date to timestamp and create a new one with the timestamp with 3 hours removed

const date = new Date()
const timestamp = date.getTime() - 3 * 3600 * 1000
const newDate = new Date(timestamp)
Pierre
  • 432
  • 1
  • 7
0
horas.getHours is not a function

Maybe horas is a plain string? In that case,

const hours = new Date(horas);
hours.setHours(hours.getHours() - 3);
// and maybe format it back to a string, if needed

should work. Otherwise, what is horas?

mbojko
  • 13,503
  • 1
  • 16
  • 26
0

transform to miliseconds than get the date in different formats

console.log(new Date(new Date().getTime() - 10800000).toISOString())
console.log(new Date(new Date().getTime() - 10800000).toUTCString())
console.log(new Date(new Date().getTime() - 10800000).toLocaleString())
codmitu
  • 636
  • 7
  • 9