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
Related
I'm trying to get the same value as 1502755200000 using momentjs
console.log(Date.UTC(2017, (8-1), 15));//1502755200000
var newDate = moment();
newDate.set('year', 2017);
newDate.set('month', 7); // April
newDate.set('date', 15);
console.log(newDate.format('X'));//1502818350
However when I try to get the miliseconds I get 1502818350 Any idea how to get the exact same timestamp as above?
Here is the fiddle https://jsfiddle.net/cdvzoezb/1/
Firstly, .format('X') gives you the unix timestamp in seconds, not milliseconds.
To get milliseconds, you must use .format('x') (lowercase x).
Secondly, when you use moment(), it gives you a moment date object at your current local time, not UTC time. So when you modify it with .set('date', 15) etc, you're setting it to 15 April 2017 in your local time. This is why you're getting the vastly different value.
To get a moment date object for current UTC time, use moment.utc().
Thirdly, the Date object you created will be at time 00:00:00.000, while the moment object will be for current time. So when you set the year/month/date, time still remains at what it was when you created the object. You need to set the moment object's time to 00:00:00.000.
This can be done with the .startOf('day') function.
In conclusion:
console.log(Date.UTC(2017, (8-1), 15)); //1502755200000
var newDate = moment.utc();
newDate.set('year', 2017);
newDate.set('month', 7);
newDate.set('date', 15);
newDate.startOf('day');
console.log(newDate.format('x')); //1502755200000
Or, much shorter:
var newDate = moment.utc('2017-07-15 00:00:00.000');
Well you can simply create a moment object out of a Date instance and then using the utc() to convert the timestamp to UTC. After that, we can use moments method format() to get milliseconds using the x display option like so:
console.log("==============");
console.log(Date.UTC(2017, (8-1), 15));
var base = Date.UTC(2017, (8-1), 15)
var newDate = moment(base);
console.log('a', newDate.utc().format('x')); //1502755200000
I need to get the difference (in minutes) from a datetime that I get froma get request in a string format to now.
According to my research, I can use moment.js to do so, but I haven't figured out now.
That format I am getting the date/time to be compared is as:
2017-02-10T20:52:13.885Z
I have already tried to do some operations with moment.js such as
moment().startof(comparedTime).fromNow())
But it returns nothing.
What are the alternatives and the best way to do this?
Can't you just use vanilla javaScript?
var getDate = '2017-02-10T20:52:13.885Z'; //get time from server
var parseDate = new Date(getDate).getTime(); //change string into Date object into milliseconds
var nowDate = Date.now(); //get current Date in milliseconds
var minutes = Math.round((nowDate-parseDate)/1000/60); //subtract times, count seconds (/1000), count minutes (/60)
console.log(minutes);
You need to create a moment object by passing the date string in. e.g.
myDate = moment(myISOString)
https://momentjs.com/docs/#/parsing/
Then you can use the moment object as described in the docs.
With Moment.js, this is simply:
moment().diff('2017-02-10T20:52:13.885Z', 'minutes') // 65
If you want partial minutes included, then pass true as a third parameter:
moment().diff('2017-02-10T20:52:13.885Z', 'minutes', true) // 65.04565
As you might know, you can display the time in JavaScript by doing Date() But can you display the Linux Epoch time in JavaScript?
I would like to know because I have a time converter and It would be nice to show the current Epoch time.
You have to use the .getTime() method of the Date object.
var d = new Date();
alert(d.getTime());
Epoch is also called timestamp.
Simple and straightforward.
var milliseconds = new Date().getTime();
Older browsers:
(new Date).getTime()
New way:
Date.now()
Returns in milliseconds, so epoch / 1000 | 0 to get seconds.
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.
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.