L
L
luntik43442015-11-05 23:16:05
JavaScript
luntik4344, 2015-11-05 23:16:05

Why is the getDay() function not working?

Hello dear users.
I have a fairly simple task - to determine the day of the week for a given date in the format dd/mm/yy. For some reason inexplicable to me, the simplest JS code gives the wrong value. For example, if you enter the date 05/11/2015 (Thursday), it returns the number 6, thinking that this day is Saturday. Here is the code:

var date=$('#inputDate').val();
var date_arr=date.split("/");
var date_obj=new Date(date_arr[2],date_arr[1],date_arr[0]);
var day=date_obj.getDay();
alert(day);

Thank you very much in advance!

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Alexey Zuev, 2015-11-05
@luntik4344

1 In the date constructor , the month parameter takes values ​​from 0 to 11 , so you need to subtract one in the 'month' parameter.
2. As noted earlier, GetDay returns values ​​from 0 - Sun. And Thursday will be 4
3. Try to name variables in camelCase style

var dateParts = '05/11/2015'.split('/'),
    date = new Date(dateParts[2], dateParts[1] - 1, dateParts[0]);

console.log(date.getDay()); // 4

PS In order not to suffer with the date on js, pay attention to momentjs

B
Bohdan Shtepan, 2015-11-05
@virtyaluk

Invalid date format. The Date constructor accepts a date in the format mm/dd/yyyy. This is the first, and secondly, getDay returns zero-based values ​​of the day of the week, where 0 is Sun, 1 is Mon, 2 is Tue, and so on.

P
Petr Yelagin, 2015-11-06
@AlienZzzz

it's better to do it differently, but like this:
var obj = $('#inputDate')
var pattern = /(\d{2})\.(\d{2})\.(\d{4})/;
var today = new Date(obj.val().replace(pattern,'$3-$2-$1'));
today.getDay() ..... well, then, as needed,
here you can do as you like - I'm talking about the date format

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question