Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Problem with dates and variables

Status
Not open for further replies.

Aviator9

Programmer
Oct 20, 2009
8
US
Hello All,

This is doing my head in; I can't understand why dates in javascript behave in this way. The second variable (T2) is different whether you write it before you set hours on the third (T3). Can anyone please explain this to me??

OUTPUT:

Sat Jan 09 2010 21:09:03 GMT+0000 (GMT Standard Time)
Sat Jan 09 2010 22:09:03 GMT+0000 (GMT Standard Time)
Sat Jan 09 2010 23:09:03 GMT+0000 (GMT Standard Time)

Sat Jan 09 2010 21:09:03 GMT+0000 (GMT Standard Time)
Sat Jan 09 2010 23:09:03 GMT+0000 (GMT Standard Time)
Sat Jan 09 2010 23:09:03 GMT+0000 (GMT Standard Time)

---
CODE:

<html>
<body>
<script type="text/javascript">
T1 = new Date(); T2 = new Date(); T3 = new Date();

document.write(T1 + "<br>");

T2.setHours(T2.getHours()+1);
document.write(T2 + "<br>");

T3 = T2

T3.setHours(T3.getHours()+1);
document.write(T3 + "<br><br>");

document.write(T1 + "<br>");
document.write(T2 + "<br>");
document.write(T3 + "<br>");

</script>
</body>
</html>
 
T3 = T2 means you have 2 different variable names that refer to the same object. When you change T3, then T2 is changed as well. If you're familiar with pointers in C/C++, both variables point to the same object.

Because you first document.write T2 before you change T3, it displays as you expect. After you assign T2 to T3 and change the hour, that means the hour for T2 (which is in the same object at T3) has changed.

If you want a different object for T3, try this:
Code:
document.write(T2 + "<br>");

[s]T3 = T2[/s]

T3.setHours(T[b][red]2[/red][/b].getHours()+1);
document.write(T3 + "<br><br>");

Lee

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top