Can you explain the variances between creating a new date object with input as "2017-01-01" and "2017-1-1" in JavaScript?

When I use new Date("2017-01-01") in the Chrome console, the output displays its hour as 8. However, when using new Date("2017-01-1") and new Date("2017-1-01"), the hour is shown as 0. This brings up the question of how new Date(dateString) actually parses the input.

new Date("2017-01-01")
// Sun Jan 01 2017 08:00:00 GMT+0800 (China Standard Time)*
new Date("2017-01-1")
// Sun Jan 01 2017 00:00:00 GMT+0800 (China Standard Time)*
new Date("2017-1-1")
// Sun Jan 01 2017 00:00:00 GMT+0800 (China Standard Time)*
new Date("2017-1-01")
// Sun Jan 01 2017 00:00:00 GMT+0800 (China Standard Time)*

Answer №1

"2017-01-01" adheres to the ES5 Date Time String format (a simplified version of ISO 8601 Extended Format) and is therefore in UTC time, equivalent to 8am in China. In Chrome, all other strings are parsed as local time.


Reference code in Chromium:

Date parsing in Chromium abides by ES5 standards with additional guidelines:

  • Any unfamiliar word before the first number is disregarded.
  • Text within parentheses is not considered.
  • An unsigned number followed by a colon denotes a time value and is included in the TimeComposer. Adding double colons or a period after a number signifies seconds and milliseconds, respectively. Other numbers indicate date components added to DayComposer.
  • A month name, or any word resembling one, is recorded as a named month in Day composer.
  • Recognizable time-zone words or patterns like (+|-)(hhmm|hh:) are identified accordingly.
  • Legacy dates do not allow extra signs or unmatched parentheses following a number, while garbage text preceding the first number is permitted.
  • Strings conforming to ES5 criteria and the specified rules will be parsed using ES5 regulations. For example, "1970-01-01" will be in the UTC time zone, not local time.

What's the significance?

Note that "2017-01-01" is interpreted in UTC due to being a "date" string without time information, aligning with the ES5 definition for such strings. If specifying a time, it follows the ISO standard and parses in local time.

Examples:

  • 2017-01-01 - Jan 1, 2017 in UTC time
  • 2017-01-01T00:00 - Jan 1, 2017 in local time
  • 2017-1-1 - Jan 1, 2017 in local time
  • 2017-(hello)01-01 - Jan 1, 2017 in local time
  • may 2017-01-01 - May 1, 2017 in local time
  • mayoooo 2017-01-01 - May 1, 2017 in local time
  • "jan2017feb-mar01apr-may01jun"
    - Jun 1, 2017 in local time

Answer №2

Exploring the difference between using new Date("2017-01-01") and new Date("2017-1-1")

The syntax new Date("2017-01-01")
strictly adheres to the specifications (details below). On the other hand, when you use new Date("2017-1-1"), it diverges from the standard and relies on any "...implementation-specific heuristics or implementation-specific date formats" that are applied by the JavaScript engine. Consequently, there is uncertainty in how or if the input will be parsed successfully, and if so, whether it will be interpreted as UTC time or local time.

Despite being compliant with the specifications, new Date("2017-01-01") has faced inconsistencies across different browser implementations over time due to its lack of timezone indicator:

  • In ES5 reference (December 2009), strings lacking a timezone indicator were supposed to be parsed in UTC. This conflicted with the ISO-8601 standard, stating that such strings should be considered local time, not UTC. Hence, in ES5, new Date("2017-01-01") was parsed in UTC.
  • ES2015 (also known as ES6, June 2015) specified that strings without a timezone indicator should be treated as local time similar to ISO-8601. Consequently, in ES2015, new Date("2017-01-01") was interpreted as local time.
  • However, this was revised in ES2016 (June 2016) following years of browsers parsing date-only forms with "-" as UTC. Therefore, starting from ES2016, only "date-only" forms like "2017-01-01" are parsed in UTC, while "date/time" forms like "2017-01-01T00:00:00" are processed in local time.

Regrettably, not all JavaScript engines conform precisely to the specifications. For instance, Chrome (version 56 at the time of writing) incorrectly interprets date/time forms as UTC instead of local time (similarly to IE9). Conversely, Chrome, Firefox, and IE11 handle date-only forms correctly by considering them as UTC. Meanwhile, IE8 does not support the ISO-8601 format since it predates the release of the ES5 spec.

Answer №3

When JavaScript parses dates, it treats ISO dates as UTC time and other date formats as local time.

According to a reference on MDN,

If the string is an ISO 8601 date, arguments are interpreted using the UTC time zone.

For instance, parsing a date string like "March 7, 2014" assumes a local timezone; however, if the format is in ISO like "2014-03-07," it will be assumed to be in UTC timezone (ES5 and ECMAScript 2015). Hence, Date objects created from these strings may correspond to different points in time depending on the version of ECMAScript supported unless the system specifies a local time zone of UTC. This means that two seemingly equivalent date strings could yield two distinct values based on their conversion format.

// When parsed, '2017-03-28' is considered UTC time,
// displayed as '2017-03-28 00:00:00' in UTC timezone,
// displayed as '2017-03-28 06:00:00' in my timezone:
console.log("ISO dates:");
var isoDates = [new Date("2017-03-28")];
for (var dt of isoDates)
{
  console.log(dt.toUTCString() + " / " + dt.toLocaleString());
}

// Other date formats are treated as local time, 
// shown as '2017-03-27 18:00:00' in my timezone,
// shown as '2017-03-28 00:00:00' in my timezone:
console.log("Other formats:");
var otherDates = [new Date("2017-3-28"), new Date("March 28, 2017"), new Date("2017/03/28")];
for (var dt of otherDates)
{
  console.log(dt.toUTCString() + " / " + dt.toLocaleString());
}

Answer №4

The date format being used here follows the International Standard (ISO format)

new Date("2017-01-01")

By sticking to this format, you can ensure consistent output across all web browsers.

On the other hand, using different date formats may lead to varying results depending on the browser since they are not as clearly defined.

For example, take a look at how this date format is handled:

new Date("2017-1-1")

This format is accepted in Chrome but triggers an error in IE 11

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Render a select field multiple instances in React

I have 5 different labels that need to be displayed, each with a select field containing the options: string, fixed, guid, disabled Below is the code I've written: class CampaignCodeRenderer extends Component { state = { defaultCampaigns: ...

There seems to be an issue with the functionality of the Bootstrap Modal

I've been working on incorporating bootstrap login Modal functionality into my code, but for some reason, the screen is not displaying it. Here's what shows up on the screen: https://i.sstatic.net/UIU2w.png The red box in the image indicates whe ...

HTML5 Websocket communication lag when using node.js

Hello everyone, thank you for taking the time to read this. I am currently utilizing NodeJS with the WS module on the server side and HTML5 WebSocket API in Firefox on the client side. The operating system being used is Windows 7 64 bit. I have encountered ...

Having a <cfinput> tag nested inside a JavaScript block is leading to errors

I'm currently working with jQuery to append a new row to a table, but I've encountered an issue when trying to insert a <cfinput> field. Strangely, ColdFusion seems to be interpreting the <cfinput> tag within the JavaScript block and ...

What is the functionality of an AngularJS Module?

I am curious about the inner workings of AngularJS modules After experimenting with AngularJS, I came across some puzzling observations. Including AngularJS without registering a module Upon including AngularJS without registering a module, I encountere ...

Leverage the power of integrating Power BI with Javascript to easily retrieve an

I have embarked on a mission to integrate PowerBI into my web application. Below is the code snippet that I have implemented: window.config = { instance: 'https://login.microsoftonline.com/', tenant: 'common', //COMMON OR YOU ...

Having difficulties sending the form information

Being new to AngularJS, I created a simple popup where users can add tasks and submit them. There is an "Add task" button that dynamically adds fields for users to enter details into. Below is the HTML markup for my popup: <div class="modal-heade ...

Exploring the features of AngularJS ui-router: ui-sref functionality and utilizing custom

My HTML looks like this: <span ui-sref="{{detailsArt(art.Id)}}" check-val></span> Within my directive check-val, I have the following code: link: function(scp, el, attr) { el.bind('click', function(event) { //some logic with ...

Tips for updating the checkbox state while iterating through the state data

In my component, I have the ability to select multiple checkboxes. When a checkbox is selected, a corresponding chip is generated to visually represent the selection. Each chip has a remove handler that should unselect the checkbox it represents. However, ...

Wordpress is experiencing a recurring issue with scripts being loaded multiple times

Currently, I am attempting to load some of my scripts from CDNs such as CDNjs and Google. While the scripts are loading correctly, I have noticed a strange issue where each script seems to generate two or even three HTTP requests (for the same script). You ...

Changing the value of the static key boolean within a react-grid-layout's layout object results in a misalignment of all grid items

tl;dr: React-grid-layout has an issue where grid items are incorrectly moved around when the static option is toggled. I want the grid items to stay in place when static and only move when users interact with them while static mode is disabled. Check out ...

Topic: Creating specific return types for methods that are chained and reusable

Here is a code snippet I am currently working on: const mixed = { validations: [] as any[], formattings: [] as any[], exceptions: [] as any[], required(message?: string) { this.validations.push({ name: 'required', message: ...

Stop the click event from firing on child elements of a parent element that is currently being dragged

Below is the structure of a UL tag in my code: <ul ondrop="drop(event)" ondragover="allowDrop(event)"> <li class="item" draggable="true" ondragstart="dragStart(event)" ondrag="dragging(event)"> <div class="product-infos"> ...

What is the best way to use a CSS class in my script specifically for specific screen sizes?

Utilizing bootstrap 4, my code is executing a for loop to generate eight divs with the class "item". To display five items per row, I am using the class "col-2". However, this results in six items being shown in a single row. Since I cannot include the o ...

In order for the user to proceed, they must either leave the zip code field blank or input a 5-digit number. However, I am encountering a problem with the else if statement

/* The user must either leave the zip code field blank or input a 5-digit number */ <script> function max(){ /* this function checks the input fields and displays an alert message if a mistake is found */ ...

Build a photo carousel similar to a YouTube channel

Is there a way to create an image slider similar to the one on YouTube channels? I've noticed that when there are multiple videos on a channel, YouTube displays them in a slider with back and forth buttons to navigate through the videos that aren&apos ...

Is it possible to activate a function in an express application when it is terminated?

I am looking for a way to handle server termination events by dumping data to disk. I'm wondering if there is a better way than logging everything in a database every few seconds using setTimeout. One possibility could be: app.on("event:terminate", ...

The problem with JQuery ajax arises when attempting to send a file input value

I am facing an issue when trying to send a file value to PHP using the ajax code below. The file gets uploaded successfully and stored in the database, but the problem arises when I get redirected. // form data submission $('#myForm').submit(fun ...

Exploring the capabilities of batch updates in Firestore with the latest web version-9

I am facing issues when trying to update certain values in my firestore collection within my nuxt project. const batch = writeBatch(firestore); const data = query(collection(firestore, `notifications`, `${uid}/news`)); const querySnapshot = await ...

Vue Loader: Multiple loaders for a single file extension

Currently, I'm experimenting with incorporating SVG into my vue-loader/webpack template project. I'm in need of loading different types of SVGs: Icons: these are utilized within my components and loaded using svg-inline loader for customizatio ...