I am into strange issue of javascript Date()
function, these are the details
Server Side : Struts (ActionForm, Action class, jsp)
Client Side : jQuery, javascript
Now, I need a server time on the page and manipulate using javascript. So, I did Calendar.getInstance().getTimeinMillis();
in the action class and save it as an ActionForm attribute.
Now, at the client side, I got the long value (timeinMillis) from the styleId. But, to manipulate, when I do
var curTime = parseInt($("#serverTime").val());
var serverTime = new Date(curTime);
Now, the serverTime is providing client machine date and not server date though we are providing timeinMillis of server.
The strange part is when I pass string value of a date instead of long timeinMillis from server and pass it as an argument, it works well.
Any idea?
This is because your javascript runs on client machine, so when you create new Date() in javascript it picks up the client machine time.
Answer to second query if you pass the sever date as string it will create date object of that date.
Use below function
function calcTime(offset) {
// create Date object for current location
d = new Date();
// convert to msec, add local time zone offsetand get UTC time in msec
utc = d.getTime() + (d.getTimezoneOffset() * 60000);
// create new Date object with supplied offset
nd = new Date(utc + (3600000*offset));
// return time as a string
return "The Server time is " + nd.toLocaleString();
}
Here you need to pass the offset of your server time with UTC
Finally resolved the issue with help of the above hints.
From java side, taken the offset from the UTC with the day light saving option.
so, in Action class
Calendar c = Calendar.getInstance();
TimeZone z = c.getTimeZone();
int offset = z.getOffset(c.getTimeInMillis());
This gives the offset of local timezone and UTC timezone including day light saving
At the javascript, I used,
var now = new Date();
var now_utc = new Date(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate(), now.getUTCHours(), now.getUTCMinutes(), now.getUTCSeconds());
var sd = new Date(now_utc.getTime() + offset);
alert("The Server time is " + sd.toLocaleString());
And, this gives correct server time with the day light saving options.
Thanks a lot for your help, without them, would not be possible to work it out. Cheers!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With