vivek vijayakumar vivek vijayakumar - 15 days ago 5
Javascript Question

JavaScript Date() differs when timezone changes

I need to convert my date to

mm-dd-yyyy
format. So I used a method like this:

var dt=new Date(2016-06-21);

var ddte='';

ddte=(("0" + (dt.getMonth() + 1)).slice(-2))+"-"+(("0" + dt.getDate()).slice(-2))+"-"+dt.getFullYear();


It works fine in my local timezone (
GMT+05:30
). But when I change my timezone to
GMT -5:00
, it gives the wrong result:
06-20-2016
. The result I want is
06-21-2016
.


  1. Can anyone please explain the problem?

  2. How can I get the correct result?

  3. Is it a bug?


Answer

Your date passed to Date() constructor will be treated as UTC time zone. Getting the time with Date.getMonth() will get your local time zone. You're probably looking for Date.getUTCMonth().

var dt=new Date("2016-06-21");

var ddte='';

ddte=(("0" + (dt.getUTCMonth() + 1)).slice(-2))+"-"+(("0" + dt.getUTCDate()).slice(-2))+"-"+dt.getUTCFullYear();

console.log(ddte);

Though in this case I see no use for using Date at all; this should suffice:

var parsedDate = "2016-06-21".replace(/(\d{4})-(\d{2})-(\d{2})/, "$2-$3-$1");
console.log(parsedDate);