Skip to content

Instantly share code, notes, and snippets.

@samwilson
Created July 19, 2011 03:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save samwilson/1091260 to your computer and use it in GitHub Desktop.
Save samwilson/1091260 to your computer and use it in GitHub Desktop.
Javascript conversion of datetime strings in PHP pages to user's timezone
$(function() {
// Get client and server timezone offsets in seconds.
var serverTimezone = $("meta[name='timezoneoffset']").attr("content");
var clientTimezone = new Date().getTimezoneOffset() * -60; // getTimezoneOffset returns (client timezone * -60)
// Get the offset between the server and client, in milliseconds.
var timezoneOffset = (clientTimezone - serverTimezone) * 1000;
$("span.datetime-convert").each(function(){
var timeToConvert = parseDatetime($(this).text());
if (timeToConvert) {
var convertedTime = new Date(timeToConvert.getTime() + timezoneOffset);
$(this).text(convertedTime.toLocaleString());
}
});
});
/**
* Convert a Y-m-d H:i:s formatted date/time string to a Date object.
*/
function parseDatetime(value) {
var a = /^(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})$/.exec(value);
if (a) {
return new Date(+a[1], +a[2] - 1, +a[3], +a[4], +a[5], +a[6]);
}
return null;
}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="timezoneoffset" content="<?php echo date('Z') ?>" />
<script src="datetimes.js" type="text/javascript"></script>
</head>
<body>
<p>Date and time: <span class="datetime-convert"><?php echo $data->datetime_column ?></span></p>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment