• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1622
  • Last Modified:

Deep Copy in Java script (Date)

Hi

how do I do a deep copy in JS, specifically with the date object.

E.g.

var now = new Date();
var tomorrow = now;// this does a shalow copy

var tomorrow.setDate( tomorrow.getDate+1);// this does will add a day to both refrences to the same date object :-(

My question is how would I do a deep copy of the now object and refer by tomorrow

regards

g2d
0
GTwoD
Asked:
GTwoD
  • 4
  • 2
  • 2
1 Solution
 
hernst42Commented:
use:

var now = new Date();
var tomorrow = new Date(now.getMilliseconds());
tomorrow.setDate( tomorrow.getDate()+1);
0
 
Michel PlungjanIT ExpertCommented:
now.getMilliseconds() ??
You mean now.getTime();
0
 
hernst42Commented:
No now.getMilliseconds() is correct.
The constuctor of Date also accepts miliseconds. AFAIK Date constructot has 5 different contruct parameters-sets, one is Milliseconds.
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
Michel PlungjanIT ExpertCommented:
Yes I know that the constructor allows milliseconds. As in getTime()
getMilliseconds will return how many milliseconds has passed since last getSecond() - e.g.

now = new Date()
tomorrow = new Date(now.getMilliseconds());

creates a date a few milliseconds after Era (Jan 1st 1970 depending on timezone)

comparable to
tomorrow = new Date(512);

where as
now = new Date()
tomorrow=new Date(now.getTime());
creates a date at the same time as now using elapsed milliseconds since Era (1970/01/01 depending on timezone)

comparable to
tomorrow = new Date(1185449647512);
0
 
Michel PlungjanIT ExpertCommented:
Try it yourself

javascript:alert( new Date(new Date(1185449647512).getMilliseconds()))
0
 
GTwoDAuthor Commented:
Thanks both,
0
 
Michel PlungjanIT ExpertCommented:
Perhaps the working version should have been the accepted solution?
0
 
GTwoDAuthor Commented:
sorry, mplungjan, you are right... I tohugt the othe version worked but it did not.

if you know a way I can retify this let me know.

g2d
0

Featured Post

Hire Technology Freelancers with Gigs

Work with freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely, and get projects done right.

  • 4
  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now