I read this code on amazon's home page.
Looks like it's trying to get the current time, However what's the meaning of using operator ||+ ?
var ue_t0=ue_t0||+new Date();
That's short-circuiting evaluation (||) followed by conversion to number (+).
That code is roughly equivalent to:
var ue_t0;
if (!ue_t0) {
ue_t0 = Number(new Date());
}
Note that converting a date to a number returns the number of milliseconds between the epoch (January 1st, 1970, 00:00:00 UTC) and that date.
It is saying :
evaluate ue_t0 and if it has value, then use it, else assign it
integer form of Date instance.
It says let ue_t0 be the value of ue_t0 or, if it is undefined, the value of the expression (new Date).
There is no ||+ operator in JavaScript, it is +new Date() which gives you a date representation in UNIX format
There is no ||+ operator.
+new Date() is a common shortcut to get the time as a timestamp. The + operator implicitly calls the valueOf method.
The || operator is another common shortcut to set a default value (+new Date()) if a variable (ue_t0) is not defined (or equal to anything that evaluates to false : null, 0 ...).
Related
I got a code like this:
var date = new Date(new Date() + dateAdjust*3600*1000 );
However, the result came out weird. But if I change the plus sign to a minus sign, and make the dateAdjust become negative, it results right. I think it considers dateAdjust36001000 as a string. How do I fix that? I heard some people say to use parseInt(), but it doesn't work either.
var date = new Date(new Date() + parseInt(dateAdjust*3600*1000) );
Please bear in mind that JavaScript operators doesn't work exactly as Google Sheets operators (mentioned because the question includes the google-sheets tag).
The fix might be to use new Date().getTime() or new Date().toValue(). This will return the date-time in milliseconds since January 1, 1970 00:00:00 UTC. Assuming that dateAjust has assigned a number, then the final code might be:
var date = new Date(new Date().getTime() + dateAdjust * 3600 * 1000 );
Explanation
In JavaScript, when using + having a Date object to the left, due to JavaScript rules, it's converted into a string. This happens because in JavaScript the + could make two possible operations, mathematical addition and string concatenation while - operator is only able to do a mathematical subtraction. This is a operation called type coercion.
Having a string to the left of +, makes the right operand to be converted into a string too.
Related
How to add days to Date?
What exactly is Type Coercion in Javascript?
Why does Date return a date instead of the object's reference when referenced?
I have a date with the format 2017-03-29T06:45:00.000Z, how do I check if it is equal or less to the date and time now?
If I check with
var currentTime = new Date();
if("2017-03-29T06:45:00.000Z" <= currentTime){
its not right since current date is in the format Wed Mar 29 2017 08:59:18 GMT+0200(CEST)
Any input appreciated, thanks
You are trying to compare a string to a Date Object. Because the two data types do not match, javascript tries to compare them by their value and calls currentTime.valueOf(). This evaluates to a integer like 1490781568805. Javascript then tries to compare the string to the evaluated integer. The result is different than you might expect, because the individual char codes of the string are compared to the integer.
"2017-03-29T06:45:00.000Z" <= new Date() // string compared to the Date object
"2017-03-29T06:45:00.000Z" <= new Date().valueOf() // javascript trying get a value for the date object
"2017-03-29T06:45:00.000Z" <= 1490781568805 // evaluates to false
You can just parse your date string to a Date object using Date.parse()
Date.parse("2017-03-29T06:45:00.000Z") <= new Date() // two Date objects are compared
this.D = new Date(1433760825 * 1000);
this.NewD = this.D.getHours();
D = "2015-06-08T10:53:45.000Z" - this is fine, it is what I was expecting to get.
But...but....NewD results to 11 and Not 10. Why???
Thanks!
When you instantiate the Date object using a value like this, you get a date based on UTC. From MDN:
Integer value representing the number of milliseconds since 1
January 1970 00:00:00 UTC (Unix Epoch).
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
When you subsequently call the getHours() method, you get the hours in your local time zone.
So for your example:
var sampleDate = new Date(1433760825 * 1000);
var hours = sampleDate.getUTCHours();
alert(sampleDate);
alert(this.hours);
Should get you the result you are looking for.
A couple of quick points:
Don't use single character variable names, and don't capitalize
them if you do
D is not equal to the date that you put in.
The new Date(value) is expecting an integer and you are giving it
something larger then an integer. So it is defaulting back to
current time.
Try using a DateString, or other method as described in this documentation:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
When you create a DateObject, if you try to print it, it will print the datetime according to UTC. But when you do the getHours() property it will tell you the hours passed according to your own local time zone.
(new DateTime()).getHours()
This will return the hours in (UTC + offset) according to your timezone.
I'm reading through a jquery plugin, and find this interesting syntax:
'sth'+ +new Date
It creates a numeric string which the author used for a unique id: sth1237004731731
I'm curious what kind of syntax it is, and if there's some reading materials about it? Thanks!
It's using some side effects of JavaScript's type coercion to build a unique identifier (probably for an element). The confusing part is the +new Date. Here, new Date (or new Date()) returns a Date object. But putting a + or a - in front of this forces the JS interpreter to coerce this value to a Number object, and the way JS does Date > Number is by returning the timestamp (or getTime()).
So this code could be expressed differently like this:
var date = new Date(), // "Mon May 14 2012 10:03:58 GMT-0400 (EST)"
timestamp = date.getTime(), // 1337004238612
identifierString = "sth" + timestamp.toString();
You might reasonably claim that there's no need to be so verbose, so I personally would probably have written this as:
var identifier = "sth" + (new Date()).getTime();
However, please avoid coding things like your example if you ever expect someone might have to maintain your code. If it stopped you in your tracks, it probably will stop a lot of people. Coding style is not merely about expressing intent to the interpreter, but expressing intent to human developers. If the code works in the browser but fails with a syntax error in most experienced developers' heads, you've done it wrong, plain and simple.
This is an interesting use of the unary + operator. Basically, you can break down this expression into three separate parts, splitting at the binary + operator:
"sth", then +, then +new Date.
The first operand of the binary + is just a generic string literal. The second operand uses the unary + operator, which, as the linked standard states, converts its operand to a Number.
Because the new operator has the highest precedence, it "binds tighter" than the unary +, which means new Date will be evaluated first. So the operand of the unary + is, in turn, the result of the expression new Date. Of course, new Date simply creates a blank Date object. As per ยง 15.9.3.3 new Date():
The [[PrimitiveValue]] internal property of the newly constructed
object is set to the time value (UTC) identifying the current time.
In other words, a new Date will just be a Date object representing the current time. And, in turn, +new Date will convert a blank Date object to a number.
The Short Answer
The specification is long and hard to follow. In short, +new Date returns the UNIX timestamp associated with the current time.
The Long Answer: Following the Spec
The long answer, following the specification, is that the unary + calls ToNumber(GetValue(expr)) where expr is the evaluated operand. GetValue(dateObj) will simply return dateObj, so the expression then becomes ToNumber(dateObj).
The result of ToNumber depends on what the type of the argument is. In the case of an object, it returns ToNumber(ToPrimitive(input argument, hint Number)).
ToPrimitive will, in turn, call the valueOf property of the Date object. That returns a Number, which is the time value associated with the Date object: finally, what we were looking for! Then it goes back up the chain: ToNumber(num) simply returns num.
Of course, from there, the string "sth" and the result of +new Date are concatenated (you can find that in the spec if you so wish), which gives you the result you were looking for.
Is it possible in javascript to convert some date in timestamp ?
i have date in this format 2010-03-09 12:21:00 and i want to convert it into its equivalent time stamp with javascript.
In response to your edit:
You need to parse the date string to build a Date object, and then you can get the timestamp, for example:
function getTimestamp(str) {
var d = str.match(/\d+/g); // extract date parts
return +new Date(d[0], d[1] - 1, d[2], d[3], d[4], d[5]); // build Date object
}
getTimestamp("2010-03-09 12:21:00"); // 1268158860000
In the above function I use a simple regular expression to extract the digits, then I build a new Date object using the Date constructor with that parts (Note: The Date object handles months as 0 based numbers, e.g. 0-Jan, 1-Feb, ..., 11-Dec).
Then I use the unary plus operator to get the timestamp.
Note also that the timestamp is expressed in milliseconds.
+(new Date())
Does the job.
The getTime() method of Date object instances returns the number of milliseconds since the epoch; that's a pretty good timestamp.