-2

I have the following code to convert a long date format in JavaScript to mm/dd/yyyy. When newValu is "Date 2016-12-29T00:00:00.000Z" from console log, date_str go back one day, becomes "12/28/2016". Not sure what is causing the problem. If we increment the d (day) by 1, that will not work, because we might need to increment the month instead, if d = 31.

                        console.log(newValue);
                        var date = newValue;
                        var d = date.getDate();
                        var m = date.getMonth() + 1;
                        var y = date.getFullYear();
                        date_str =  (m<=9 ? '0' + m : m) + '/' + (d <= 9 ? '0' + d : d) + "/" + y;
Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
user1187968
  • 7,154
  • 16
  • 81
  • 152

2 Answers2

0

Here a tip:

    function change(date) {
        var r = String(date).match(/^\s*([0-9]+)\s*-\s*([0-9]+)\s*-\s*([0-9]+)(.*)$/);
        return r[2] + "-" + r[3] + "-" + r[1] + r[4];
    }

This function will return a "mm/dd/yyyy".

mchl0208
  • 59
  • 2
  • 10
0

Not sure what is causing the problem.

If newValue is a Date object and when printed to the console you get "2016-12-29T00:00:00.000Z", note that that is GMT.

If the host system has a time zone west of GMT (say -0400) then the equivalent date will be "2016-12-28T20:00:00.000Z", i.e. 4 hours earlier (and on the previous day). When you use plain get methods (getDate, getHours, getMinutes, etc.), it's these values you're getting.

So your date string is correct for the time zone of the host system.

var x = new Date('2016-12-29T00:00:00.000Z');

// Local equivalent on your host system
document.write(x);

// UTC values in ISO 8601 format
document.write('<br>' + x.toISOString());

// Date string from ISO parts
document.write('<br>'+ ('0'+(x.getUTCMonth()+1)).slice(-2) + '-' +
               ('0'+x.getUTCDate()).slice(-2) + '-'  +
               x.getUTCFullYear() );

If you want the values in your date string to match the UTC values of the Date object, then use UTC methods:

var d = date.getUTCDate();
var m = date.getUTCMonth() + 1;
var y = date.getUTCFullYear();
RobG
  • 142,382
  • 31
  • 172
  • 209