How to subtract hours from a date in javascript?

4

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

var data = new Date();

How did you hours from that date?

    
asked by anonymous 25.07.2016 / 20:18

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);
    
25.07.2016 / 20:23
1

You can get it by 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);

Demo:

$('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:<inputtype="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>
    
25.07.2016 / 20:54