1
var dt_now = '2-22-2013';//mm-dd-yyyy, this is dynamic in actual code
            dt_now = dt_now.split("-");
            dt_now = addZero(dt_now[2])+'-'+addZero(dt_now[0])+'-'+addZero(dt_now[1]);
            dt_now = new Date(dt_now);

I am using the above code to convert a user defined text to actual date for use in rest of my code. it seems to work ok for me but on another system which is situated in a different timezone(my time -12 hours), the date comes out as February 21st instead of Feb 22nd, that is, it is running one day behind the expected date. I have no idea how to fix this or what the error might be. Any suggestions?

Bluemagica
  • 5,000
  • 12
  • 47
  • 73

2 Answers2

0

In the method that outputs the date you need to use getUTC* instead of get*, i.e. getUTCDate(). To generate a date object with UTC info refer to the second answer in How do you convert a JavaScript date to UTC?

Community
  • 1
  • 1
filmor
  • 30,840
  • 6
  • 50
  • 48
0

To avoid timezone issues, use UTC. You don't have to rely on a library; simple ISO 8601 date strings would be sufficient. See Date.prototype.toISOString for making one from a Date (compatibility).

Constructing is as simple as new Date('yyyy-mm-ddT00:00Z'), so you just need a minor change to your code to create a Date

var dt_now = '2-22-2013';//mm-dd-yyyy, this is dynamic in actual code
dt_now = dt_now.split("-");
dt_now = addZero(dt_now[2])+'-'+addZero(dt_now[0])+'-'+addZero(dt_now[1])+'T00:00Z';
dt_now = new Date(dt_now);

The Z indicates UTC. I include a time (T00:00) so it matches that which would be generated by toISOString.

Paul S.
  • 64,864
  • 9
  • 122
  • 138