Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getMonth getUTCMonth difference result

Tags:

javascript

I found and inconsistent result when using the JavaScript date.getMonth() and date.getUTCMonth(), but only with some dates. The following example demonstrates the problem:

<!DOCTYPE html>
<html>
<body onload="myFunction()">

<p id="demo">Click the button to display the month</p>

<script type="text/javascript">
function myFunction()
{
var d = new Date(2012, 8, 1);
var x = document.getElementById("demo");
x.innerHTML=d;
x.innerHTML+='<br/>result: ' + d.getMonth();
x.innerHTML+='<br/>result UTC: ' + d.getUTCMonth();

}
</script>

</body>
</html>

The output of this example is:

Sat Sep 01 2012 00:00:00 GMT+0100 (Hora de Verão de GMT)
result: 8
result UTC: 7

If i change the date to (2012, 2, 1) the output is:

Thu Mar 01 2012 00:00:00 GMT+0000 (Hora padrão de GMT)
result: 2
result UTC: 2

In the first example, getMonth returns 7 and getUTCMonth returns 8. In the second example, both returns the same value 2.

Does anyone already experiences this situation? I am from Portugal and i think that it has something to be with my GMT but i don't understand why this is happening, because the examples are running in same circumstances.

Thanks in advances

like image 260
bruno.almeida Avatar asked Aug 07 '12 13:08

bruno.almeida


People also ask

What does getMonth() return?

The getMonth() method returns the month in the specified date according to local time, as a zero-based value (where zero indicates the first month of the year).

What is getUTCMonth?

The getUTCMonth() returns the month of the specified date according to universal time, as a zero-based value (where zero indicates the first month of the year).


1 Answers

Universal Time Zone date methods are used for working with UTC dates

Date returns month between 0 to 11 new Date(1976, 01 , 18) - Wed Feb 18 1976 00:00:00 GMT+0530 (India Standard Time)

*getUTCDate return same as getDate() but returns Date based on World Time Zone, same with month and year

new Date(1976, 01 , 18).getUTCDate() - 17

new Date(1976, 01 , 18).getDate() - 18

new Date(1976, 02 , 18).getUTCMonth() - 2

new Date(1976, 01 , 18).getMonth() - 1

new Date(1976, 01 , 18).getYear() - 76

new Date(1976, 01 , 18).getUTCFullYear() - 1976

new Date(1976, 01 , 18).getFullYear() - 1976

like image 107
Parul Avatar answered Oct 02 '22 13:10

Parul