
Result2 = Fri 17:44:54 GMT-0500 (Eastern Standard Time) Result1 = Fri 12:44:54 GMT-0500 (Eastern Standard Time) Var result5 = new Date(dateToMilliseconds+(-3600000*5)) Var result3 = new Date(dateToMilliseconds+(3600000*24))

Var result2 = new Date(dateToMilliseconds+(3600000*5)) Below are some examples of adding hours to a date object with the help of the getTime() method. We can also add negative milliseconds to subtract hours from a date. This will create a new date that will be 5 hours ahead of the current date Var addedHours = dateToMilliseconds + (3600000*5) Var dateToMilliseconds = date1.getTime() Since there are 3600000 milliseconds in 1 hour, we can add multiples of 3600000 to our converted date to add as many hours as we want. The getTime() method converts dates into the number of milliseconds since January 1st, 1970. ago"Īlert( formatDate(new Date(new Date - 5 * 60 * 1000)) ) // "5 min.To add hours to a date, we can use the JavaScript getTime() method. If (diff component.slice(-2)) // take last 2 digits of every component Let diff = new Date() - date // the difference in milliseconds For instance, browser has performance.now() that gives the number of milliseconds from the start of page loading with microsecond precision (3 digits after the point): JavaScript itself does not have a way to measure time in microseconds (1 millionth of a second), but most environments provide it. Sometimes we need more precise time measurements. Note that unlike many other systems, timestamps in JavaScript are in milliseconds, not in seconds.


They may tweak results of “artificial tests” compared to “normal usage”, especially when we benchmark something very small, such as how an operator works, or a built-in function. Modern JavaScript engines perform many optimizations. That may lead to wrong results.įor more reliable benchmarking, the whole pack of benchmarks should be rerun multiple times.

And by the time of running bench(diffGetTime) that work has finished.Ī pretty real scenario for a modern multi-process OS.Īs a result, the first benchmark will have less CPU resources than the second. Imagine that at the time of running bench(diffSubtract) CPU was doing something in parallel, and it was taking resources. Wow! Using getTime() is so much faster! That’s because there’s no type conversion, it is much easier for engines to optimize. Return date2.getTime() - date1.getTime() įor (let i = 0 i < 100000 i++) f(date1, date2) Īlert( 'Time of diffSubtract: ' + bench(diffSubtract) + 'ms' ) Īlert( 'Time of diffGetTime: ' + bench(diffGetTime) + 'ms' )
