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.
getDay() The getDay() method returns the day of the week for the specified date according to local time, where 0 represents Sunday.
JavaScript does not have a date data type. However, you can use the Date object and its methods to work with dates and times in your applications. The Date object has a large number of methods for setting, getting, and manipulating dates. It does not have any properties.
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:
Passing a string to the Date constructor calls Date.parse, which is largely implementation dependent and differs between browsers even for the standardised parts.
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 (e.g. 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 (i.e. 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]);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With