Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can I get the current date minus 20 seconds in javascript?

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
like image 773
user3147580 Avatar asked Jan 01 '14 23:01

user3147580


People also ask

How do you subtract time in JavaScript?

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.

Can you subtract dates in JavaScript?

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.

How do I subtract minutes from a date in JavaScript?

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.

How do I get the difference between two dates and seconds in JavaScript?

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.


2 Answers

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(); }
}
like image 129
cookie monster Avatar answered Sep 21 '22 07:09

cookie monster


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.

like image 27
Michael Geary Avatar answered Sep 18 '22 07:09

Michael Geary