Paolo Broccardo
Paolo Broccardo

Reputation: 1744

Display date and time according to the user's time zone in Coldfusion

I need to display datetime values in my application according to the logged in user's local timezone. I would like my app to be able to detect the user's timezone automatically then display the adjusted server date and time accordingly.

How do you do this in Coldfusion?

I am looking for a solution that does NOT prompt the user to select their time zone at any point, like Facebook.

Thanks

Upvotes: 4

Views: 7199

Answers (4)

Nil Liew
Nil Liew

Reputation: 11

if you're using cfwheels.org and your users doesnt mind to see "yesterday" or "10 minutes ago"... then the TimeAgoInWords() is what you need.

Upvotes: -1

Ben Doom
Ben Doom

Reputation: 7885

Instead of having CF do the formatting, I would push a standardized date representation (like UTF( and have JavaScript format the date. That way, the date is formatted to whatever timezone is set on the computer.

This avoids wrong lookups near zone change areas, dealing with daylight savings vs. areas where it isn't observed, and people traveling (formatting to "home time" vs. "local time").

Added:

This dumps the current time in a long format. It's semi-off-the-cuff, so you'll want to look at the JavaScript Date Object's methods for more formatting options.

<cfset n = dateconvert("local2utc",now())>
<script>
 d = new Date();
 d.setUTCFullYear(#dateformat(n, "yyyy")#);
 d.setUTCMonth(#dateformat(n, "m")#);
 d.setUTCDate(#dateformat(n, "d")#);
 d.setUTCHours(#timeformat(n, "H")#);
 d.setUTCMinutes(#timeformat(n, "m")#);
 document.write(d.toLocaleString());
</script>

Upvotes: 11

Andreas Schuldhaus
Andreas Schuldhaus

Reputation: 2648

ColdFusion is a server side language. So you can't determine the timezone of a client in a direct way.

You can use JavaSript on the client side, find out the timezoneoffset and send it via an Ajax request to ColdFusion.

JavaScript:

var clienttime = new Date();
var time = clienttime.getTimezoneOffset()/60;

Then on the server side you can use the offset to calculate the date you want to show the user.

You can also lookup the country of the client using the client IP, but then you have to use an external service to get the country for a certain IP and you have to deal with problems like daylight savings and multiple timezones per country.

Upvotes: 6

Stephen Moretti
Stephen Moretti

Reputation: 2438

It would be quicker and more accurate if you did just ask your user to specify their timezone as part of their login profile; set once and forget.

Otherwise, you're looking at doing an IP address look up and determining where that IP address is based, determining the timezone and then displaying the time accordingly. Even if you store the information in a cookie or session variable, its a bit of a faff when you could just ask your user what timezone they are in.

Upvotes: 1

Related Questions