Will Ashley Will Ashley - 3 months ago 19
HTML Question

Javascript date objects always one day behind

I am trying to convert a date object from the backend db to a string to present on the view, however, when I convert it, the result is always one day behind.

The code:

date = this.props.date;

d = new Date(date)
options = {
month: "long", weekday: "long", year: "numeric",
day: "numeric"
};

dateStr = d.toLocaleDateString("en-us",options)


EDIT examples provided:
Regarding backend structure, the date is inserted into the database via a simple html datepicker form.

Currently, this.props.date, if rendered on the view, will render something like this:

"2016-10-01"


When I use the code above, it would become:

"Friday, September 30, 2016"

Answer

Assuming your backend date is in UTC specifically ISO8601 and you want the displayed date to be UTC in en-us language-region.

var date = "2016-10-01";
var parts = date.split('-');
parts[1] -= 1;
var d = new Date(Date.UTC.apply(null, parts));
options = {
  month: "long",
  weekday: "long",
  year: "numeric",
  day: "numeric",
  timeZone: 'UTC'
};

document.getElementById('out').textContent = d.toLocaleDateString("en-us", options);
<pre id="out"></pre>

Assuming the date is UTC and the Date object handles ISO8601 correctly (some older versions do not) then you could rely on the built in parsing of Date.

var date = "2016-10-01";
var d = new Date(date);
options = {
  month: "long",
  weekday: "long",
  year: "numeric",
  day: "numeric",
  timeZone: 'UTC'
};

document.getElementById('out').textContent = d.toLocaleDateString("en-us", options);
<pre id="out"></pre>

So all I have done is explicitly set the output to be UTC, otherwise it is using your runtime's default time zone. Worth noting that toLocaleDateString is still in its infancy and can vary across browsers, just like ISO8601 parsing.