Search code examples
javascriptdateutc

Date.UTC() returns last day of previous month while getUTCFullYear(), getUTCMonth() returns correctly first day of correct month


I'm getting a strange result:

   var date = new Date();
   var year  = date.getMonth() < 11 ? date.getFullYear() : date.getFullYear() + 1;
   var month = date.getMonth() < 11 ? date.getMonth() + 1 : 0;

   console.log(new Date(Date.UTC(year, month)));

   var utcYear = date.getUTCMonth() < 11 ? date.getUTCFullYear() : date.getUTCFullYear() + 1;
   var utcMonth = date.getUTCMonth() < 11 ? date.getUTCMonth() + 1 : 0;

   console.log(new Date(utcYear, utcMonth));

With the particular date I'm using (any date will do), Date.UTC gives me:

Sun May 31 2015 19:00:00 GMT-0500 (Central Daylight Time)

The getUTC... aproach gives me:

Mon Jun 01 2015 00:00:00 GMT-0500 (Central Daylight Time)

Am I mis-using Date.UTC or am I missing something?

Thanks


Solution

  • You are creating a Date using UTC time, but then you are displaying it in local time, that's why it's a few hours behind. Use Date.prototype.toUTCString() to see the UTC time

      var date = new Date();
      var year = date.getMonth() < 11 ? date.getFullYear() : date.getFullYear() + 1;
      var month = date.getMonth() < 11 ? date.getMonth() + 1 : 0;
    
      // It's a UTC date, display it as UTC, not local time
      console.log(new Date(Date.UTC(year, month)).toUTCString());
    
      var utcYear = date.getUTCMonth() < 11 ? date.getUTCFullYear() : date.getUTCFullYear() + 1;
      var utcMonth = date.getUTCMonth() < 11 ? date.getUTCMonth() + 1 : 0;
    
      // Created using local time, you can just use the normal toString()
      console.log(new Date(utcYear, utcMonth));