Show Local Time

From CodeCodex

I get annoyed by Web sites that show dates/times local to some time zone completely removed from where I am. Why not show users times in their local zone?

Here's an example of how to do it. The example time is 1979 Mar 15 21:30:00 UTC, but this will be converted to your local time:

TheTime = 290381400
document.write(new Date(TheTime * 1000).toLocaleString())

Note this assumes that the formatted string will not contain any HTML specials in it. To be really safe, you could wrap the toLocaleString call in a call to EscapeHTML.

It is also nice to let the user enter times in timezone-local format, and convert them internally to UTC. To do this, define two HTML form fields, one for the user to type into and the other to hold the internal UTC value, e.g.

<form name="example" action= ... >
What's the time, Mister Wolf?
<input name="time_internal" type="hidden" value="">
InitialTime = ...
document.write("<input type=\"text\" name=\"time_display\" size=\"50\" value=\"")
document.write(new Date(InitialTime * 1000).toLocaleString())
function validate_time()
  /* called on form submission to validate value in field "time". */
    var TheForm = document.forms["example"]
    var Internal = Date.parse(TheForm.elements["time_display"].value)
    if (!isNaN(Internal))
        TheForm.elements["time_internal"].value = Internal
        alert("bad time entered")
      } /*if*/
  } /*validate_time*/
<button type="button" onmouseup="validate_time()">Submit</button>

When the form is submitted, you ignore the time_display parameter and use the value of time_internal instead.

It's probably a good idea to provide an initial default value for the input field, as done above; this gives the user a better idea of the syntax they need to stick to.