vivek vijayakumar vivek vijayakumar - 1 year ago 56
Javascript Question

JavaScript Date() differs when timezone changes

I need to convert my date to

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 (
). But when I change my timezone to
GMT -5:00
, it gives the wrong result:
. The result I want is

  1. Can anyone please explain the problem?

  2. How can I get the correct result?

  3. Is it a bug?

Answer Source

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();


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");

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download