var timeInMs = Date.now();
per MDN
vs.
var timeInMs = new Date(optional).getTime();
per MDN.
Is there any difference between the two, besides the syntax and the ability to set the Date (to not the current) via optional in the second version?
Date.now() is faster - check out the jsperf
These things are the same (edit semantically; performance is a little better with .now()):
var t1 = Date.now();
var t2 = new Date().getTime();
However, the time value from any already-created Date instance is frozen at the time of its construction (or at whatever time/date it's been set to). That is, if you do this:
var now = new Date();
and then wait a while, a subsequent call to now.getTime() will tell the time at the point the variable was set.
They are effectively equivalent, but you should use Date.now(). It's clearer and about twice as fast.
Edit: Source: http://jsperf.com/date-now-vs-new-date
When you do (new Date()).getTime() you are creating a new Date object. If you do this repeatedly, it will be about 2x slower than Date.now()
The same principle should apply for Array.prototype.slice.call(arguments, 0) vs [].slice.call(arguments, 0)
Yes, that is correct; they are effectively equivalent when using the current time.
Sometimes it's preferable to keep some time tracking variable in a Date object format rather than as just a number of milliseconds, to have access to Date's methods without re-instantiating. In that case, Date.now() still wins over new Date() or the like, though only by about 20% on my Chrome and by a tiny amount on IE.
See my JSPERF on
timeStamp2.setTime(Date.now()); // set to current;
vs.
timeStamp1 = new Date(); // set to current;
http://jsperf.com/new-date-vs-settime
I tried to find the extracly answer for your question. I found a page with a benchmark so clearly.
The static Date.now() method returns the number of milliseconds elapsed since January 1, 1970 00:00:00 UTC.
The getTime() method returns the number of milliseconds since the ECMAScript epoch.
You can use this method to help assign a date and time to another Date object. This method is functionally equivalent to the valueOf() method.
Source: https://developer.mozilla.org/
ex:
const moonLanding = new Date('July 20, 69 20:17:40 GMT+00:00');
console.log('getTime:::', moonLanding.getTime()); // expected output: -14182940000
console.log('valueOf:::', moonLanding.valueOf()); // expected output: -14182940000
Date.now() is calling the static method now() of the class Date.
While new Date().getTime() can be divided into two steps:
new Date(): Call the constructor() method of Date class to initialize an instance of Date class.
Call getTime() method of the instance we just initialize.
MDN web docs classifies Date.now() into static method of Date, and Date.prototype.getTime() into instance method.
Related
I'm using moment.js and I want to write a test that says, "If you do not pass in a date, it returns now()". The problem is, every time the test runs, now() will be a different result. In other libraries, you can set what now() will return for testing purposes. Does moment.js provide a way to do that? I've been googling and not finding any results that say whether or not you can do this.
Timekeeper (https://www.npmjs.com/package/timekeeper) fills this exact need.
It overrides the date constructors (which moment uses under the hood) so it will work for moment as well.
You can do the following:
const timekeeper = require('timekeeper');
const freezeDate = new Date();
timekeeper.freeze(freezeDate);
// in your test
expect(result).to.equal(freezeDate);
You can change the time source (which basically overrides the implementation with a new Date.now) before each test by doing the following from the official momentjs docs. This returns the number of milliseconds since unix epoch time (1/1/1970).
moment.now = function () {
return +new Date();
}
I am having a lot of trouble doing something that seems obvious. I have a date:
Date.now()
I want it in milliseconds from epoch. I cannot get that to work. I have tried:
Date.now().getTime();
(Date.now()).getTime();
Date.now().getMilliseconds();
(Date.now()).getMilliseconds();
var date = Date.now();
var ms = date.getTime();
var ms = date.getMilliseconds();
All of these fail because apparently getTime() and getMilliseconds() (which I don't think is the correct approach anyways) are apparently not functions.
What am I doing wrong here?
Date.now() already returns ms from epoch, not a Date object...
Date.now is a method in the Date namespace1, same as Math.random is for Math.
Date (unlike Math) is also a constructor. Used like new Date(), it will return a Date object.
1. A property of Date, which is a function/object
You already have the value you want.
var numberOfMillisecondsSinceEpoch = Date.now();
You're attempting to call methods on a Date object, such as you'd get for the current date by calling new Date(). That's not necessary or appropriate if you're using Date.now(), which returns a number instead.
For platforms that don't provide Date.now(), you can convert the current Date object to a number to get the same value.
var numberOfMillisecondsSinceEpoch = Number(new Date());
Number(new Date()) === Date.now() // if your system is quick enough
I want to make a Javascript date object eg. var now = new Date().getTime() that is set for "tomorrow at 8am", how would I accomplish that?
You could do the following:
var now = new Date();
now.setDate(now.getDate() + 1)
now.setHours(8);
now.setMinutes(0);
now.setMilliseconds(0);
also check this
You could also: var now = Date("2016-03-23T8:00:00");
And var now = new Date(2016,03,23,8,0,0,0 );
If you have a lot of date arithmetics, I can only strongly recommend the use of moment.js.
Using this library, your code would be as short as moment().add(1, 'days').hours(8).startOf('hour').
moment.js works with 'moment' objects that wrap over JS dates to provide additional methods. The moment() invocation returns a moment of the current datetime, thus being the moment.js equivalent to new Date().
From there we can use the moment.js methods, as add(quantity, unit) that adds a duration to the previous date. All these manipulation methods return a modified moment, which mean we can chain them.
The hours() methods is both a getter and a setter depending on its arguments ; here we provide it with a number, which mean we set the moment's hour part to 8. A call to .hours() would have instead returned the current hour part.
startOf(unit) returns a moment at the start of the unit, meaning it will set all lesser units to 0 : moment().startOf('day') would return today's 00:00 am.
I have this code and I run it in chrome
var time = new Date("2014-02-11 19:30:00" + ' UTC');
This gives me back exactly what I need, it transforms the date I'm passing to my local time. Even this one does the exact same thing
var time = new Date("2014-02-11T19:30:00");
The problem is that the first function is not working in Mozilla and the second one doesn't transform the date to my local timezone. I need to do the transformation in both explorers (actually in all of them) but it would be great for it to at least work in those two.
This should work on both:
Note: TZD = time zone designator (Z or +hh:mm or -hh:mm)
new Date("1994-11-05T13:15:30Z")
Creates a JavaScript Date instance that represents a single moment in time. Date objects are based on a time value that is the number of milliseconds since 1 January, 1970 UTC.
Constructor
new Date();
new Date(value);
new Date(dateString);
new Date(year, month [, day, hour, minute, second, millisecond]);
It is the definition of the Date object to use values 0-11 for the month field.
I believe that the constructor using a String is system-dependent (not to mention locale/timezone dependent) so you are probably better off using the constructor where you specify year/month/day as seperate parameters.
BTW, in Firefox,
new Date("04/02/2008");
works fine for me - it will interpret slashes, but not hyphens. I think this proves my point that using a String to construct a Date object is problemsome. Use explicit values for month/day/year instead:
new Date(2008, 3, 2);
Is there anything readily available in JavaScript (i.e. not through "plugins") that allows me to do something like setTimeout, but instead of saying in how many milliseconds something should happen, I give it a date object telling it when to do something?
setToHappen(function () {
alert('Wake up!');
}, new Date("..."));
And yes, I know I can do this by simply subtracting new Date() with my existing date object (or maybe it's the other way around) to get the amount of milliseconds, but I'd still like to know.
You have to compute the number of milliseconds between now and your date object:
function setToHappen(fn, date){
return setTimeout(fn, date - Date.now());
}
NB Please note #calvin's answer: this will not work if the number of milliseconds is greater than 2147483647.
Since people are talking about calculating timeout intervals using date objects, it should be noted that the max value setTimeout() will accept for the interval parameter is 2147483647 (2^31 - 1) as PRIntervalTime is a signed 32-bit integer. That comes out to just under 25 days.
No, but you could easily write your own function. Just calculate the diference between now and the given moment in miliseconds and call setTimeout with that.
Something like this:
setToHappen = function(fn, date){
var now = new Date().getTime();
var diff = date.getTime() - now;
return setTimeout(fn, diff);
}
EDIT: removed the extra multiplication by 1000, thanks chris for pointing that out!
You can simply subtract Date.now() from the date
const myDate = new Date('...');
setTimeout(func, myDate - Date.now());