How to subtract hours from a javascript date?

Asked

Viewed 4,795 times

4

I have a variable that receives the current date and I need to subtract hours from that date.

var data = new Date();

Like subtraction of hours of that date?

  • how many hours exactly?

  • any quantity. Can be 5, 6, whatever

  • you don’t want to format the date first?

  • That I already did. I just wasn’t getting the subtraction of the hours rs

2 answers

8


make a combination of setHours with getHours.

Date.prototype.addHours = function (value) {
  this.setHours(this.getHours() + value);
}

var data = new Date();
console.log(data);

data.addHours(-30);
console.log(data);

  • 2

    @Samirbraga, added the function.

  • 2

    Now it’s more than flexible, I like it.

  • Just what I needed!

1

You can get it using getTime().

Then subtract in milliseconds when you want to return.

// Defina o quanto quer voltar:

var Dia = 0;
Dia = Dia*60*60*24

var Hora = 1;
Hora = Hora*60*60;

var Minuto = 30;
Minuto = Minuto*60

var Segundos = 0;
Segundos = Segundos*1;

unix = new Date().getTime() - ((Dia+Hora+Minuto+Segundos)*1000);
resultado = new Date(unix);

Demonstration:

$('input').on('keydown, keyup', function(){
      
    var Dia = $('[name=Dia]').val() !== '' ? parseInt($('[name=Dia]').val())*60*60*24 : 0;
    
    var Hora = $('[name=Hora]').val() !== '' ? parseInt($('[name=Hora]').val())*60*60 : 0;
    
    var Minuto = $('[name=Minutos]').val() !== '' ? parseInt($('[name=Minutos]').val())*60 : 0;
    
    var Segundos = $('[name=Segundos]').val() !== '' ? parseInt($('[name=Segundos]').val())*1 : 0;
        
    unix = new Date().getTime() - ((Dia+Hora+Minuto+Segundos)*1000);
    $('x').text(new Date(unix));
    
});

$('x').text(new Date());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>Dias: <input type="number" name="Dia" value="0"></label> <br><label>Hora: <input type="number" name="Hora" value="0"></label> <br><label>Minutos: <input type="number" name="Minutos" value="0"></label> <br><label>Segundos: <input type="number" name="Segundos" value="0"></label> <br><x></x>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.