views:

54

answers:

1

How can I use JavaScript to add a message like this to a web page:

Our office hours are 9am - 5pm (09:00 - 17:00) PST.

In your timezone, that's WWxx - YYzz (AA:00 - BB:00).

Where:

  • "WW" and "YY" are converted to the proper values for "hour" (on the 12 hour clock).

  • "xx" and "zz" are converted to either "am" or "pm".

  • "AA" and "BB" are converted to the proper value for "hour" (on the 24 hour clock).

So... an example of the final output would be:

Our office hours are 9am - 5pm (09:00 - 17:00) PST.

In your timezone, that's 12am - 8am (00:00 - 08:00).

+2  A: 

JavaScript provides a toLocaleTimeString method on date objects that you can use to format time according to the user's locale. This, however, suffers from the problem of being too specific for you needs as it will display the full time including hours, minutes, seconds, and optionally the AM/PM designator in places that use it.

06:42:12 PM // 12 hour
18:42:12    // 24 hour

Note that you are not displaying the minutes for the translated local time, which may be a problem as 9am for you might be 4:30pm for someone. Here's a modified solution to what you have listed.

Our office hours are 9:00am - 5:00pm (09:00 - 17:00)
In your timezone, that's 07:30am - 3:30pm (07:30 - 15:30).

You already know your local time. To get the time local to the site visitor, get the unix timestamp for when your office starts and closes for any given day. Let's say those timestamps are:

1279401823511 // start
1279430623511 // end

Just create a date object with these times, and then format the time for the user.

var open = new Date(1279401823511);
var close = new Date(1279430623511);

Writing a function to get the date in both 12/24 hour formats is simple. See this for a reference. I will use the toString function from Date.JS as it makes life a little easier.

var localTime = "In your timezone, that's {a} - {b} ({c} - {d})";
var map = {
    '{a}': open.toString('h:mmtt'),
    '{b}': close.toString('h:mmtt'),
    '{c}': open.toString('HH:mm'),
    '{d}': close.toString('HH:mm')
};
for(var p in map) {
    localTime = localTime.replace(p, map[p]);
}
console.log(localTime); 
"In your timezone, that's 2:23PM - 10:23PM (14:23 - 22:23)    
Anurag