how can I get the current date minus 20 seconds in javascript? I can not figure out how to subtract 20 seconds to the current date in javascript how can I do, I get a negative value in this way
There is an easier way? thanks
var currentDate = new Date()
var day = currentDate.getDate()
var month = currentDate.getMonth() + 1
var year = currentDate.getFullYear()
var ora = currentDate.getHours()
var minuti = currentDate.getMinutes()
var secondi = currentDate.getSeconds()-20
setHours(date. getHours() - numOfHours); return date; } // 👇️ Subtract 1 hour from the current date const result = subtractHours(1); // 👇️ Subtract 2 hours from another date const date = new Date('2022-04-27T08:30:10.820'); // 👇️ Wed Apr 27 2022 06:30:10 console.
To subtract days from a JavaScript Date object, you need to: Call the getDate() method to get the day of the Date object. Subtract the number of days you want from the getDate() returned value. Call the setDate() method to set the day of the Date object.
First we will use the getTime() method to get the total milliseconds of the date. After that, we will subtract the minutes from the total milliseconds in the form of milliseconds. Users can multiply the minutes by 60 seconds * 1000 milliseconds to convert the minutes tomilliseconds.
let x = new Date(); let y = new Date(); let dif = Math. abs(x - y) / 1000; Here, we find the number of seconds between two dates – x and y. We take the absolute difference between these two dates using the Math.
Give this a shot:
new Date(Date.now() - 20000);
The Date.now()
returns the milliseconds since Jan 1, 1970 00:00:00, so we just subtract 20000 milliseconds from that, and use the result to create a new date.
As @rjz noted, you'll need a shim for old IE. The MDN shim is below:
if (!Date.now) {
Date.now = function() { return new Date().getTime(); }
}
I would do it something like this:
function DateOffset( offset ) {
return new Date( +new Date + offset );
}
var twentySecondsAgo = DateOffset( -20000 );
// Should differ by 20 seconds (modulo 60)
alert(
twentySecondsAgo.getSeconds() +
'\n' +
new Date().getSeconds()
);
With this code you don't need any shims or polyfills or any of that stuff. I just tested it in IE 5.5 and Netscape 4.79 and it works fine there! That's why I used alert()
in the test instead of console.log()
, so I could test it in those old browsers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With