the_mind_ has asked for the wisdom of the Perl Monks concerning the following question:

How can i get the clients local time from a cgi script?
Do i have to use a perl/javascript combo or is there a module for doing this?

Replies are listed 'Best First'.
Re: Client's time/date?
by jryan (Vicar) on Aug 19, 2001 at 22:33 UTC
    No, Time::Local would return the server's local time, not the client's, since perl is a server-side language. To find the client's local time (without them directly inputting it), you have to use a client-side language, such as javascript, store it in a hidden input field, and then have it submitted when they submit the form. You could try something like:
    <form name="theform" action="getmytime.pl"> <input type="hidden" name="user_localtime"> </form> <script language="Javascript1.2"> function set_user_localtime() { // find out if the script has already been called if ( typeof already_submitted == "undefined" ) { // create new date var datevar = new Date(); var timestring = datevar.toLocaleString(); // set the hidden field's value to the local time document.theform.user_localtime.value=timestring; // submit the form document.theform.submit(); } return 1; } </script> <body onLoad="set_user_localtime())">
    (the submitted value will look something like this: 08/18/01 17:28:35) Then you need a perl script that handles that. The perl script could re-write the page, but make sure that you also have something like that assures that the script isn't called again, and is printed right after the content-type header:
    # tells the javascript that the script as already been run print "<script>var already_submitted=1;</script>";
    Finally, you can find their offset by formatting the submitted value to be similar to perl's localtime like so:
    use CGI; $query = CGI::new; $user_localtime = $query->param("user_localtime"); @user_l = split (' ', $query); @user_time = split (':', $u_l[1]); @server_localtime = localtime; $offset = $user_time[0] - $server_localtime[2]; print $offset;
    $offset will be the difference between the server's local time and the user's local time.
      Thanks! Exactly what i needed!
Re: Client's time/date?
by Moonie (Friar) on Aug 19, 2001 at 21:47 UTC
    Check out Time::Local.

    Update: my bad.. don't listen to me.

      That won't do what the original question was asking for. Remember a CGI program runs on the server, so that module would render server time. The questioner wanted the time on the client, which implies asking the user agent (browser) what the time is on its box.

      To my knowledge, that does require Javascript or Java running on the client machine. I don't know of a way to ask the user agent to run a Perl program.

      HTH