Javascript: Set a new Date to tomorrow 8am - javascript

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.

Related

Can I assign what "now" is using Moment.js?

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();
}

Converting Year, Month, Day to momentjs Unix timestamp

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

How to get time using Moment JS

I've two javascript variables: startDate and endDate. I want to store the current time(unix timestamp in ms) to endDate and timestamp of 24 hours before in startDate. I'll use this two variables to query the records for last 1 day. How can I do that using moment JS?
Have you looked at the website yet? It's full of examples - http://momentjs.com/ I think what you are trying to do is as simple as
var startDate = moment(endDate).subtract(1, 'days');
Following your question more literally, you can do this:
var endDate = moment(); //the current time
Or, you can just ignore the endDate part of this problem and go straight to startDate with
var startDate = moment().subtract(1, 'days'); //one day before the current time
Finally, if you need to format it a certain way, you can apply a formatting rule such as:
moment().subtract(1,'days').format('YYYY-MM-DD h:mm:ss a')
Use format without an argument and it gives you ISO 8601 format
moment().subtract(1,'days').format() //eg: "2015-04-04T01:53:26-05:00"
This worked for me although I have never found it in the docs. Should have been published but it works.
Try:
moment(currentTime).format("hh:mm"));or
var currentTime = moment();
console.log("CURRENT TIME: " + moment(currentTime).format("hh:mm"));
For those who are looking for a way to get timestamp, just do it:
moment().valueOf()
I think what you are looking for is something like
moment(endDate).unix()
which returns something like:
1435161240
You can even calculate the time from now using
moment(endDate).fromNow()
which returns something like:
"2 days ago"
You can directly call function momentInstance.valueOf(), it will return numeric value of time similar to date.getTime() in native java script.

JavaScript Date function not working in Firefox

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);

Performance - Date.now() vs Date.getTime()

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.

Categories