Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript dates are a day off? [duplicate]

I am trying to use a simple date function in my application to pass a date in the format of yyyy-mm-dd such as 2017-07-30 and have it returned in the format of 07/30/2017.

However, when I try this, I supply my date correctly but it outputs one day shorter than what I am looking for.

function format(inputDate) {
    var date = new Date(inputDate);
    if (!isNaN(date.getTime())) {
        var day = date.getDate().toString();
        var month = (date.getMonth() + 1).toString();
        // Months use 0 index.

        return (month[1] ? month : '0' + month[0]) + '/' +
           (day[1] ? day : '0' + day[0]) + '/' + 
           date.getFullYear();
    }
}

console.log(format('2017-07-30'));

Here is a fiddle: http://jsfiddle.net/49pptrj4/

Any thoughts as to why this is returning incorrectly?

Result on my end:

enter image description here

like image 726
SBB Avatar asked Jan 30 '23 21:01

SBB


1 Answers

From here

Given a date string of "March 7, 2014", [Date.]parse() assumes a local time zone, but given an ISO format such as "2014-03-07" it will assume a time zone of UTC.

Your date string is assumed to be 0:00, or midnight, on the date specified in UTC, the time zone of Greenwich, England. Your browser however takes this time and converts it to your local timezone, which is a few hours behind UTC if you're in the Americas, making the result a day behind.

The following code should work for creating a Date in the local timezone with the correct date.

utcDate = new Date("2017-07-30"); //Date object a day behind
new Date(utcDate.getTime() + utcDate.getTimezoneOffset() * 60000) //local Date

Here the local Date is created by adding time based on the time zone difference. getTimezoneOffset() returns in minutes, so * 60000 is needed to convert to milliseconds.

This might not work in areas ahead of UTC; it might advance an extra day. Edit: Just checked and getTimezoneOffset() is negative in areas ahead of UTC so it will subtract time correctly.

like image 72
Matthias Avatar answered Feb 03 '23 07:02

Matthias