Difference between Date(dateString) and new Date(dateString)
Date()
With this you call a function called Date()
. It doesn't accept any arguments and returns a string representing the current date and time.
new Date()
With this you're creating a new instance of Date.
You can use only the following constructors:
new Date() // current date and time
new Date(milliseconds) //milliseconds since 1970/01/01
new Date(dateString)
new Date(year, month, day, hours, minutes, seconds, milliseconds)
So, use 2010-08-17 12:09:36
as parameter to constructor is not allowed.
See w3schools.
EDIT: new Date(dateString)
uses one of these formats:
- "October 13, 1975 11:13:00"
- "October 13, 1975 11:13"
- "October 13, 1975"
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 writeDD/MM/YYYY
. - Now let's imagine that user picked
21 December 2014
(formatted as21/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's2nd Jan
but user picked1st Feb
). Do you want to make it more complicate? Evennew 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.
What are the technical differences between new Date(Date.parse(string)) and new Date(string)?
I ended up finding the answer to this question shortly after I wrote it. According to the ECMAScript Language Specification, for a string argument these two approaches will yield identical results in standards-compliant browsers.
From the ECMAScript Language Specification:
15.9.3.2 new Date(value):
Call ToPrimitive(value).
If Type(Result(1)) is String, then go to step 5.
...
- Parse Result(1) as a date, in exactly the same manner as for the parse method (15.9.4.2); let V be the time value for this date.
When new Date(string)
is called, it parses the string in the exact same way as Date.parse(string)
would. So by calling new Date(Date.parse(string))
we get the exact same result as new Date(string)
, but at the performance cost of an extra method call.
What is the difference between Date(d.getTime()) and new Date(d.getTime()) in javascript?
Date(x)
returns a string representing the current time, the arguments are ignored.
See date constructor called as a function in the specs. This is the expected behavior.new Date(x)
returns aDate
object initialized with x.
See one-argument variant of the date constructor.
What is the difference between new Date().getTimezoneOffset() and new Date(string).getTimezoneOffset()?
The getTimezoneOffset
function returns the offset from UTC for the local time zone that applies to the moment in time represented by the Date
object instance you call it on.
If you call it on
new Date()
, you're asking for the current offset, as the default constructor sets theDate
object's timestamp to the current value, as also given byDate.now()
.If you call it on
new Date(value)
, you're asking for the offset that applies to the moment in time represented by that value.
Time zone offsets are not fixed, but rather they are established by governments and can easily change. One reason they change is due to daylight saving time (DST), which may or may not apply to a given time zone for part of the year. Other reasons they might change is due to governmental policies around modifying the observance of DST, the start and stop dates or times of DST, or a change to the standard time offset. Since these sorts of changes create historical differences, it is necessary to know which point in time you are asking about when you ask for the offset from UTC with getTimezoneOffset
.
You can read more about this in the section titled "Time Zone != Offset" in the timezone tag wiki.
One other thing - the format you provided for the string ("2020/03/01") is non-standard. It may or may not be supported by a given JavaScript engine, but it is not part of the specification. Instead, you should use either "2020-03-01"
(if you mean midnight UTC on that date), or "2020-03-01T00:00:00"
(if you mean midnight local time on that date).
Javascript new Date(dateString) handling
When you create a new Date
object passing a dateString
parameter to the constructor, it gets parsed using the Date.parse()
method. Now, quoting from the MDN documentation (emphasis mine):
Differences in assumed time zone
Given a date string of
"March 7, 2014"
(or"03/07/2014"
),parse()
assumes a local time zone, but given an ISO format such as"2014-03-07"
it will assume a time zone of UTC. ThereforeDate
objects produced using those strings will represent different moments in time unless the system is set with a local time zone of UTC.
Therefore, since that your are giving the second string in the ISO format, and your local time zone is UTC+6, you're getting a date which is six hour behind yours, because it gets calculated as UTC+0. In fact:
Apr 07 1984 18:00:00 = Apr 08 1984 00:00:00 - 06:00:00
Mystery solved!
How to find date difference from Date in string format in javascript
You can convert them to dates using
function convertToDate(str)
{
var dateArr = str.split("/");
return new Date(dateArr[2], dateArr[1], dateArr[0])
}
var date1 = convertToDate("1/11/2015");
var date2 = convertToDate("15/11/2015");
var diffInDays = (date1.getTime() - date2.getTime())/ (1000*60*60*24);
alert( Math.ceil( Math.abs( diffInDays ) ) );
getTime
returns number of milliseconds since 1970, so you need to convert them to days by dividing it with 24 * 60 *60 * 1000
()
how to compare two string dates in javascript?
var d1 = Date.parse("2012-11-01");
var d2 = Date.parse("2012-11-04");
if (d1 < d2) {
alert ("Error!");
}
Demo Jsfiddle
Recently found out from a comment you can directly compare strings like below
if ("2012-11-01" < "2012-11-04") {
alert ("Error!");
}
Related Topics
Chrome Extension - Get Dom Content
What Is the "Hasclass" Function with Plain JavaScript
Capture Browser Console Logs with Capybara
Valueof() VS. Tostring() in JavaScript
JavaScript Function Leading Bang ! Syntax
(...()) VS. (...)() in JavaScript Closures
Template Language That Works on Both Server and Client
Meteor: Calling an Asynchronous Function Inside a Meteor.Method and Returning the Result
Override Console.Log(); for Production
Rails 5 - Turbolinks 5,Some Js Not Loaded on Page Render
How to Create Query Parameters in JavaScript
How to Use JavaScript in Ruby on Rails
Why Is It Frowned Upon to Modify JavaScript Object's Prototypes