Date VS New Date in JavaScript

Date vs new Date in JavaScript

From the specs:

When Date is called as a function rather than as a constructor, it returns a String representing the current time (UTC).

and:

When Date is called as part of a new expression, it is a constructor: it initialises the newly created object.

So, new Date(...) returns an object such that obj instanceof Date is true, whereas Date(...) basically returns the same as new Date().toString().

JavaScript - difference between Date(), new Date(), and ISODate

The difference is that 2016-09-26T19:17:04.731Z related to GMT0 timezone and Mon Sep 26 2016 15:17:04 GMT-0400 (EDT) to your local timezone. Both are point to the same time :)

You can read more about data formats and timezones in Wiki

date = new Date(); date.valueOf() vs Date.now()

There are several ways to get the current time in JavaScript:

  • new Date() creates a Date object representing current date/time
  • new Date().valueOf() returns number of milliseconds since midnight 01 January, 1970 UTC
  • new Date().getTime() Functionally equivalent to new Date().valueOf()
  • Date.now() Functionally equivalent to the 2 methods above

As mentioned in the comments and MDN links, Date.now() is not supported in Internet Explorer 8. So if IE 8 compatibility is a concern you should use new Date().valueOf() at the cost of slightly diminished code readability.

Or if you want to use Date.now() but must be compatible with browsers which don't support it, you can place following code somewhere in your JavaScript files, which will add support for it.

if (!Date.now) {
Date.now = function() {
return new Date().getTime();
}
}

Javascript new Date vs new Date Object

The first example results in an object with keys based on the user's locale's string representation for dates, each containing the same value as a Date object. This is not particularly useful, in part because the keys will differ depending on the user's locale, and because in order to access the value of one of those keys, you would need to know the date that matches it... which is the value you'd be looking up in the first place.

The second example results in an empty object (because it just references each "key", without assigning a value to it.)

var eventDates = {};eventDates[new Date('10/04/2017')] = new Date('10/04/2017');eventDates[new Date('10/06/2017')] = new Date('10/06/2017');eventDates[new Date('10/20/2017')] = new Date('10/20/2017');eventDates[new Date('10/26/2017')] = new Date('10/26/2017');console.log(eventDates);
var eventDates2 = {};eventDates2[new Date('10/04/2017')];eventDates2[new Date('10/06/2017')];eventDates2[new Date('10/20/2017')];eventDates2[new Date('10/26/2017')];
console.log(eventDates2)

javascript: `Date()` and `new Date()`

It is a documented behavior:

Note: JavaScript Date objects can only be instantiated by calling JavaScript Date as a constructor: calling it as a regular function (i.e. without the new operator) will return a string rather than a Date object; unlike other JavaScript object types, JavaScript Date objects have no literal syntax.

You can find it in ECMAScript 1st edition already, from 1997 (https://www.ecma-international.org/publications/files/ECMA-ST-ARCH/ECMA-262,%201st%20edition,%20June%201997.pdf):

15.9.2.8 Date()
A string is created and returned as if by the expression new Date ().toString()

Difference between Date.now(), new Date().getTime(), and +new Date

Date.now() gives you the timestamp right now.

Date.getTime() gives you the timestamp of a date object that may represent a moment in the past or future.

+new Date is a slightly confusing way of saying "create a new Date object, then convert it to a number" (identical to new Number(new Date()), and when you convert a Date to a number, it returns the date's timestamp (i.e. getTime().

Use #1 if you want the timestamp right this second, and use #2 if you want to get the timestamp of a Date object you got from somewhere else. Don't use #3 ever - it might look clever, but all you're doing is writing code that's going to confuse yourself or someone else later.

(Side point, the reason new Date works is because you don't actually need parentheses to create an object if you are passing no parameters. You should still use empty parameters though for readability if nothing else.)

Date() vs Date().getTime()

I get that it wasn't in your questions, but you may want to consider Date.now() which is fastest because you don't need to instantiate a new Date object, see the following for a comparison of the different versions:
http://jsperf.com/date-now-vs-new-date-gettime/8

The above link shows using new Date() is faster than (new Date()).getTime(), but that Date.now() is faster than them all.

Browser support for Date.now() isn't even that bad (IE9+):

https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date/now

Javascript: Difference between `new Date(dateString)` vs `new Date(year, month, day)`

No, they're not the same (even assuming you'll subtract one month later: he's doing mdy[0] - 1) because new Date(str) is required (by standard, see §15.9.4.2) to accept only date in a specific format ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ, see also this post, I won't repeat myself here):

If the String does not conform to that format [ISO 8601] the function may fall back to any implementation-specific heuristics or implementation-specific date formats.

Please note (as pointed out by Royi in comments) that also RFC 2822 should be supported (according to MDN) but it's not mentioned in JavaScript specifications and Internet Explorer doesn't officially support it (see MSDN, it can parse something similar but it's not the same).

In that code they're parsing using a specific locale rules (MM/DD/YYYY, I suppose en-US locale but it's not only one). To be honest I wouldn't even use that code for parsing (because yes, actually it'll be broken for a different locale: even separator used for splitting is not "locale safe"). Let me explain with an example:

  • You're using a proper configured date time picker (or <input type="date"/> when supported) you'll enter date according to your locale. For example in Italy (but in general in Europe) we write DD/MM/YYYY.
  • Now let's imagine that user picked 21 December 2014 (formatted as 21/12/2014 according to his locale).
  • With string splitting that code will fail (because it'll pick 21 as month number, obviously it's not valid). Even worse than that such errors may even go unnoticed (for example if user picks 1/2/2014 code will "think" it's 2nd Jan but user picked 1st Feb). Do you want to make it more complicate? Even new Date(str) may fail because it's browser dependent (and you can't really trust heuristic to be portable and safe).

If you're asking yourself "Then why they used such code?" I'd say that they used a quick workaround to support dates using en-US locale (probably because browser they used didn't support them with heuristic guess) but it's not something you should reuse.

Solution? Do not ever parse date by hand (unless you really and deep know what you're doing), use a good library (for example moment.js) for that because most assumption you may do about date formatting are...wrong.

Why does 'Date()' return a string?

MDN describes this behavior right below the top "Syntax" section:

Note: The only correct way to instantiate a new Date object is by using the new operator. If you simply call the Date object directly, such as now = Date(), the returned value is a string rather than a Date object.

It's described in the specification here:


  1. If NewTarget is undefined, then

    a. Let now be the Number that is the time value (UTC) identifying the current time.

    b. Return ToDateString(now).

Regarding JavaScript new Date() and Date.parse()

Above format is only supported in IE and Chrome.

so try with another formats. following are some formats and there supporting browsers.

<script type="text/javascript">

//var dateString = "03/20/2008"; // mm/dd/yyyy [IE, FF]

var dateString = "2008/03/20"; // yyyy/mm/dd [IE, FF]
// var dateString = "03-20-2008"; // mm-dd-yyyy [IE, Chrome]
// var dateString = "March 20, 2008"; // mmmm dd, yyyy [IE, FF]
// var dateString = "Mar 20, 2008"; // mmm dd, yyyy [IE, FF]

// Initalize the Date object by passing the date string variable
var myDate = new Date(dateString);
alert(myDate);
</script>


Related Topics



Leave a reply



Submit