简体   繁体   中英

javascript getDay() returns wrong number for a date in america but it returns correct value in india

I was trying to get the week day name using javascript getDay(). I know getDay() method returns the day of the week, like: 0 is sunday, 1 is monday etc.

var d=new Date("2014-05-26"); //this should return 1 so weekname monday.
alert(d.getDay()); // in india it returns correct value 1 fine.

But when i checked this code in USA it returns wrong number 0(sunday).

Can anybody tell me why is this happening?? I dont know where i'm doing wrong.

Thanks in advance.

Date constructor creates an instance using UTC, which differs from local time in both India and the US. You can check that by comparing

d.toLocaleString()

and

d.toUTCString()

So, what you probably need is

d.getUTCDay()

which returns the same result for all time zones.

You have two issues:

  1. Passing a string to the Date constructor calls Date.parse , which is largely implementation dependent and differs between browsers even for the standardised parts.

  2. ISO 8601 dates without a timezone are specified in ES5 to be treated as UTC , however some browsers treat them as local (and ES6 will change that so they should be treated as local)

So if you want consistent dates, write your own parser to turn the string into a date. Presumably you want strings without a time zone to be local, so:

function parseISODate(s) {
  var b = s.split(/\D/);
  var d = new Date();
  d.setHours(0,0,0,0);
  d.setFullYear(b[0], --b[1], b[2]);
  return d.getFullYear() == b[0] && d.getDate() == b[2]? d : NaN;
}

The above function expects a date in ISO 8601 format without a timezone and converts it to a local date. If the date values are out of range (eg 2014-02-29) it returns NaN (per ES5). It also honours two digit years so that 0005-10-26 reuturns 26 October, 0005.

And:

parseISODate('2014-05-26').getDay() // 1

everywhere.

A simplistic version without the above (ie doesn't validate date values and turns years like 0005 into 1905) that can be used if you know the date string is always valid and you don't care about years 1 to 99 is:

function parseISODate(s) {
  var b = s.split(/\D/);
  return new Date(b[0], --b[1], b[2]);
}

try this,

var d=new Date("2014-05-26"); //this should return 1 so weekname monday.
var newDate = Date.UTC( d.getFullYear(), d.getMonth(), d.getDate());
alert(newDate.getDay()); // in india it returns correct value 1 fine.

you can produce same issue via changing your system date time zone change. set it to UTC -5/4/3 or UCT +5/4/3 and test this code

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM