Javascript getDay () returns invalid number for date in america but returns correct value in india

I tried to get the name of the day of the week using javascript getDay (). I know the getDay () method returns the day of the week, for example: 0 - Sunday, 1 - 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 the USA, it returns the wrong number 0 (Sunday).

Can someone tell me why this is happening? I do not know where I am doing wrong.

Thanks in advance.

+4
source share
3 answers

You have two problems:

  • Passing a string to the Date constructor calls Date.parse , which is highly implementation dependent and differs between browsers even for the standardized part.

  • ISO 8601 ES5 UTC, ( ES6 , )

, , , . , , , :

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;
}

ISO 8601 . (, 2014-02-29), NaN ( ES5). , 0005-10-26 26 0005 .

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

.

(.. , 0005 1905), , , , 1 99

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

UTC, , . ,

d.toLocaleString()

d.toUTCString()

, , ,

d.getUTCDay()

.

+4

try it,

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 the same problem by changing the time zone change of your system date. install it in UTC -5/4/3 or UCT +5/4/3 and test this code

+1
source

Source: https://habr.com/ru/post/1544271/


All Articles