问题
var date1 = new Date();
date1.setFullYear(2011, 6, 1);
// 2011-07-01, ok
console.log(date1);
// set date2 the same date as date1
var date2 = date1;
// ...
// now I'm gonna set a new date for date2
date2.setFullYear(2011, 9, 8);
// 2011-10-08, ok
console.log(date2);
// 2011-10-08, wrong, expecting 2011-07-01
// I didn't assign a new date to date1
// WHY is date1 changed?
console.log(date1);
回答1:
Date is object , so it is assigned as reference - simple approach is
date2 = new Date( date1 );
回答2:
Both date variables are just references to the same date object in memory. So you need date2
to be a clone of date1
. Change:
var date2 = date1;
to this:
var date2 = new Date(date1.getTime());
回答3:
date2
It's a reference to date1
.
To achieve the expected results, do the following:
var date1 = new Date();
date1.setFullYear(2011, 6, 1);
var date2 = new Date();
date2.setTime(date1.valueOf());
回答4:
JavaScript uses pass by reference for Dates* (as well as all non-primitives -- var o = {}; var j = o; j.foo = 1; console.log(o.foo); //1
. On the other hand, for Numbers, Strings, and Booleans var o = 0; var j = o; j++; console.log(j); // 0
), so that is expected behavior.
If you need to copy a date you can always
var date2 = new Date( date1.getTime() );
* Please see comments to understand why this is not entirely correct.
回答5:
You need to create a copy of date1
, currently date1
and date2
refer to the same date object.
var date2 = new Date(date1.valueOf());
回答6:
Variation of @SergeS's answer, but Date() objects in js coerce to number, so you don't need getTime():
// general case
var dateValueCopy = new Date(date1);
And restated with OP variable names:
var date2 = new Date(date1);
回答7:
<html lang="en">
<head>
<script>
function getDateDiff(time1, time2) {
var str1= time1.split('/');
var str2= time2.split('/');
var t1 = new Date(str1[2], str1[0]-1, str1[1]);
var t2 = new Date(str2[2], str2[0]-1, str2[1]);
var diffMS = t1 - t2;
console.log(diffMS + ' ms');
var diffS = diffMS / 1000;
console.log(diffS + ' ');
var diffM = diffS / 60;
console.log(diffM + ' minutes');
var diffH = diffM / 60;
console.log(diffH + ' hours');
var diffD = diffH / 24;
console.log(diffD + ' days');
alert(diffD);
}
//alert(getDateDiff('10/18/2013','10/14/2013'));
</script>
</head>
<body>
<input type="button" onclick="getDateDiff('10/18/2013','10/14/2013')" value="clickHere()" />
</body>
</html>
来源:https://stackoverflow.com/questions/6609574/javascript-date-variable-assignment