Reputation: 3246
In my JSP page I am trying to display local date and time with timezone. It can be JavaScript, jQuery or JSTL whichever is easy.
I tried <fmt:formatDate value="<%= new java.util.Date() %>" pattern="MMM d, hh:mm a z"/>
but time is coming as CDT even I changed my time zone to Eastern.
I need in this pattern May 22, 10:34 AM EDT
.
Any suggestion?
Upvotes: 1
Views: 1951
Reputation: 1156
If you want to know the timezone of the client relative to GMT/UTC here you go:
var d = new Date();
var tz = d.toString().split("GMT")[1].split(" (")[0]; // timezone, i.e. -0700
If you'd like the actual name of the timezone you can try this:
var d = new Date();
var tz = d.toString().split("GMT")[1]; // timezone, i.e. -0700 (Pacific Daylight Time)
UPDATE 1
Per the first comment by you can also use d.getTimezoneOffset() to get the offset in minutes from UTC. Couple of gotchas with it though.
The sign (+/-) of the minutes returned is probably the opposite of what you'd expect. If you are 8 hours behind UTC it will return 480 not -480. See MDN or MSDN for more documentation. It doesn't actually return what timezone the client is reporting it is in like the second example I gave. Just the minutes offset from UTC currently. So it will change based on daylight savings time. UPDATE 2
While the string splitting examples work they can be confusing to read. Here is a regex version that should be easier to understand and is probably faster (both methods are very fast though).
If you want to know the timezone of the client relative to GMT/UTC here you go:
var gmtRe = /GMT([\-\+]?\d{4})/; // Look for GMT, + or - (optionally), and 4 characters of digits (\d)
var d = new Date().toString();
var tz = gmtRe.exec(d)[1]; // timezone, i.e. -0700
If you'd like the actual name of the timezone try this:
var tzRe = /\(([\w\s]+)\)/; // Look for "(", any words (\w) or spaces (\s), and ")"
var d = new Date().toString();
var tz = tzRe.exec(d)[1]; // timezone, i.e. "Pacific Daylight Time"
Upvotes: 1
Reputation: 100
You can get the client Date using Javascript Date Object.
var clientDate = new Date();
//for day clientDate.getDate();
//for month client.getMonth()
Then you get difference with UTC using
clientDate.getTimezoneOffset();
//This returns -120 for GMT+2,
Upvotes: 0