What does this javascript variable mean? - javascript

When I create variables I don't use brackets after equal sign.
Why does this code use brackets after equal sign? Can anyone explain this? I want to know what does it mean after equal sign.
var start = (new Date).valueOf(),

The paranthesis around new Date cause that to be evaluated first, so the date is created, and THEN call valueOf on the newly created date.
It's basically like doing
var d = new Date();
var start = d.valueOf();
but on one line.
However, it should be (new Date()).valueOf(). What is there right now will error out.

the intention of this is to shorten the following code:
var date = new Date();
var start = date.valueOf();
but you can't write:
var start = new Date().valueOf();
because theres no Date().valueOf() that can be used as constructor, so you'll have to add braces. the part in braces will be executed first (creating a new date), and valueOf() will be called on the result of the code in braces (read: on the constructed date). That said, the solution is what we got in your question:
var start = (new Date).valueOf();
the result of all this is a timestamp in milliseconds.

This method returns the equivalence of the Date object in milliseconds.
The milliseconds are expressed as an integer representing the number of milliseconds between midnight January 1, 1970 (GMT) to the date and time specified in the Date object.

Easy thing. new Date returns a date. Without brackets, it would be new Date.valueOf(). Since Date doesn't have a method valueOf(), this results in an error.
BUT, an instance of Date has this function. So we use brackets. (new Date).valueOf() is the same as
var start = new Date;
start.valueOf();

The wrapping parens around new Date evaluates the call to create a Date object then calls a method of the date object -> valueOf. An easier to understand example would be
(3 + 2) + 2; // = 7 - evaluates 5 then adds 2
the valueOf method is defined as:
Returns the primitive value of a Date object. Overrides the Object.prototype.valueOf method.
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date
You can actually achieve the same thing by
var start = +(new Date())
// returns the integer value of the date (in milliseconds)
// aka the primitive value

Related

Convert integer to Date in node.js

I'm trying to convert a integer to a Date using node .js, and Date.
I know that this is a very common question but all the solutions that have been posted before have failed to help me.
I am getting the dates from a json file found at http://api.guardian.gg/chart/elo/4611686018432537994,
Example date: 1461110400000
What I've tried:
var date = String(new Date(elodata.x));
and
var date = String(new Date(parseInt(elodata.x)));
But I get invalid date as a result.
I realise that this might not be doable because I don't know how guardian.gg handles this data. But you never know.
You can pass in your value directly to a Date constructor in Javascript if it is an integer (which it appears to be in :
var date = new Date(elodata.x);
Likewise, you can also use the the setTime() function in Javascript to pass your integer value in if you already have an existing object :
var date = new Date();
d.setTime(elodata.x);
Example
var d1 = new Date(1461110400000);
console.log(`Constructor: ${d1}`);
var d2 = new Date();
d2.setTime(1461110400000);
console.log(`setTime(): ${d2}`);
When a single argument is passed to the Date constructor, if it's a string it will be parsed. The result of that is implementation dependent but if 1461110400000 is a string it will almost certainly give an invalid date.
If given a number, it's treated as a time value. So if you're passing a number, make sure it's type number:
var timeValue = '1461110400000';
console.log( new Date(+timeValue));
You could also use Number(timeValue) or parseInt(timeValue) but unary + is less to type.

Javascript: Set a new Date to tomorrow 8am

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.

Why is it possible to subtract Date objects in javascript? Is there any form of operator overloading?

Why is the below code actually working?
Code
var firstDate = new Date();
// some time passing here
var secondDate = new Date();
// Difference seems to contain difference in miliseconds.
var difference = secondDate - firstDate;
What I get is, I believe, an equivalent to secondDate.getTime() - firstDate.getTime(). The only question is, how can this conversion to number of milliseconds happen in background? Is this some sort of operator-overloading?
The operator - converts the operands to numbers (check for example "12"-3). The date object defines a numeric conversion .valueOf() that returns the number of milliseconds.
See also for example +(new Date).

JavaScript Pointers and Dates

I noticed this situation in my code (unfortunately), and was able to duplicate it in my own JS file. So I have this code:
var date1 = new Date(); // today
var date2 = date1;
date2 = date2.setDate(date2.getDate() + 1);
// what is date1?
After this code executes, date1 is today's date + 1! This harkens back to my undergrad days when I learned about pointers, and I guess I'm a little rusty. Is that what's happening here? Obviously I've moved the assignment away from date1, and am only modifying date2, but date1 is being changed. Why is this the case?
Incidentally, after this code executes date2 is a long number like 1272123603911. I assume this is the number of seconds in the date, but shouldn't date2 still be a Date object? setDate() should return a Date object.
Classic case of Rerence Types vs. Value Types.
When the assignment operator works on
primitive values (numbers, strings,
Boolean, null, and undefined), a copy
of the value is made. When the
assignment operator works on
JavaScript objects, references to the
objects are copied.
Assignment by Value Versus Assignment by Reference
Therefore:
// creates a new Date object in memory with date1 as a Reference to its location
var date1 = new Date();
// date2 will now point to the same Object in memory as date1
var date2 = date1;
// Since both date1 and date2 point to the same object,
// modifying one changes the other
date2 = date2.setDate(date2.getDate() + 1);
As for the resulting value, you're correct. It's getting converted inside the expression to the number of seconds since Epoch.
Your variables date1 and date2 are pointing to the same object.
That's why the when you execute the setDate on the date2 variable, you see the change on date1, because actually the two variables point to the exact same object.
_____ ____________
|date1| --------->| new Date();|
¯¯¯¯¯ ¯¯¯¯¯^¯¯¯¯¯¯
_____ |
|date2| -----------------
¯¯¯¯¯
The setDate method returns the valueOf the Date object after changing it, which is a numeric representation, milliseconds since 01 January, 1970 UTC until your date.
both your variables reference the same object, and the setDate() call actually changes the object itself (in other words, it doesn't just clone the original and return the new one)
When you use a Date object in an expression it can end up being cast to a number, which (as you say) is the number of seconds since the epoch.
This code:
var date1 = new Date(); // today
var date2 = date1;
...creates one date object, which has two references to it. Since both variables point to the same object, any changes to the object are visible using either variable. They both point to the same thing. The thing stored in the variable is the reference to the object, not the actual object.
The best way to think about it (and indeed literally what's happening) is that variables contain values. Full stop. With primitives like (say) the number 5, the value held by the variable is the value. With object references, the value held by the variable is a reference to (pointer to) the object, not the actual object. For all we know, that reference is the number 77314 which is an index into some lookup table somewhere containing the actual object data. We don't know (or care), it's just a value that gets us to the object.
The rules for what happens with assignment, passing values into functions, etc., are identical in both situations — values are values. So:
var n1, n2;
n1 = 5; // n1 has the value 5
n2 = n1; // n2 now also has the value 5
And:
var d1, d2;
d1 = new Date(); // d1 has a value that references the new Date object
d2 = d1; // d2 now also has that value, which references that object
When you change the object's properties, it doesn't have any effect on the reference to the object. The object's properties belong to the object, not to the reference to the object. So since the two variables point to (refer to) the same thing, if you change that thing using one of the variables, you see the changes if you query the object using the other variable.

How to create object of Date("23.03.2010")

I have astring directly coming form the database and I am creating object of Date as
Date dt=Date("23.03.2010") and it is comin NaN
whereas when I use Date dt= Date("03/23/2010") it works fine.
Any Idea how I can get this working?.
You can parse the string from the database and then create the date object. You will have to subtract 1 from the parsed month value to get a correct date.
var dateString = "23.03.2010";
var dateParts = dateString.split(".");
var dt = new Date(dateParts[2], dateParts[1] - 1, dateParts[0]);
You must pass string (parsed) dates in MDY format. This is to prevent ambiguity (does 5/6/2010 mean 6th May or 5th June?)
If you prefer, you can use new Date(year, month, day) format, and pass the arguments separately.
The safest way if is you can return the date as milliseconds since 1970-01-01, then you can easily create a Date object from it. Example:
var n = 1269302400000;
var dt = new Date(n);
Note that you'll want to invoke Date with the new operator - from the Mozilla Developer Center:
Invoking Date in a non-constructor
context (i.e., without the new
operator) will return a string
representing the current time.
The same page details the syntax of the Date constructor.
If you are constructing a Date from a string the format accepted is governed by the rules of the Date.parse method. See Microsoft's Date.parse documentation for a summary of these rules.
Give this a try...
var dateParts = '23.03.2010'.split('.');
// -1 from month because javascript months are 0-based
var dateObj = new Date(dateParts[2], dateParts[1]-1, dateParts[0]);
try
d="23.03.2010".split(".");
Date dt=Date([d[1],d[0],d[2]].join("/"))
i think it isn't the most beautiful way.

Categories