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
LVL 1
GTwoDAsked:
Who is Participating?
 
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
 
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
Ultimate Tool Kit for Technology Solution Provider

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy now.

 
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
 
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
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.