-2

I want to make code to execute a task 3 seconds before a given time.

Something like this:

var Time = new Date('December 25, 1995 08:00:00:000');
Time.getSeconds() - 3 ;

This should give me 57, instead of -3

VLAZ
  • 26,331
  • 9
  • 49
  • 67

1 Answers1

1

You need to set the seconds via the the dedicated method first - the logic to handle such “rollovers” is already implemented in there - and then you read it again:

// var Time = new Date('December 25, 1995 08:00:00:000');
// careful with the above date format, not all browsers will parse this correctly
// modified version, for this example:
var Time = new Date('1995-12-25T08:00:00');
Time.setSeconds( Time.getSeconds() - 3 );
console.log(Time.getSeconds());
CBroe
  • 91,630
  • 14
  • 92
  • 150
  • 1
    Should work [better than this](https://i.imgur.com/lajk92i.png) if the date was valid. [Demo](https://jsbin.com/vatonay/1/edit?js,console) – VLAZ Apr 15 '21 at 11:49
  • @VLAZ yes, good point. Fabio, the date format used in the initial example does not work in all browsers - see https://stackoverflow.com/questions/2587345/why-does-date-parse-give-incorrect-results – CBroe Apr 15 '21 at 11:51