You'd think that getting the local time of a users computer would be easy. Unfortunately when I was looking for this, too many websites were too confusing and only eventually did I cobble together something that worked for me.
The standard PHP way to get the UNIX time stamp is:
time();
This returns the number of seconds since the beginning of UNIX time.
However, this PHP function retrieves the server time and not the local time for a web visitor.
Because PHP runs on the server it cannot know what the browser time is unless something sends the time back.
JavaScript was the answer for me as follows:
<script type="text/javascript">
var offset = new Date().getTimezoneOffset() / 60 * (-1);
document.write('<INPUT TYPE="hidden" NAME="offset" VALUE="' + offset + '">');
</script>
This simple code takes the JavaScript date and converts it to a number of hours offset. Whether + or -.
In your PHP form handler simply convert this offset to seconds and add to the server timestamp as follows:
<?php
$tstamp = time(); //server
$cleanoffset = addslashes($form['offset']); //in hours as '-hrs' or 'hrs'
$timestamp = $tstamp + ($cleanoffset*60*60); //add offset in seconds
?>
Note here my incoming form fields were added to an array called form[] as follows:
<?php
if (isset($_POST)) {
$form = array();
foreach($_POST as $var => $val) {
$form[$var] = cleanData($val); //clean and to array
}
}
?>
You can see I passed my incoming form data through a cleanData() function as well.
If you are looking to validate an timezone offset like this which may or may not have the leading '-' then use something like this:
<?php
if(!preg_match("/^-?[0-9]+$/", $form['offset'])) {$errors[] = "The timezone offset ".$form['offset']." format is not correct. Someone is hacking the input values!";}
?>
You can see I am also using an $errors[] array to store my form fields errors.