See also my Code Review question: Javascript conversion of datetime strings in PHP pages to user's timezone. Kudos to Aleksi Yrttiaho.
Created
July 19, 2011 03:41
-
-
Save samwilson/1091260 to your computer and use it in GitHub Desktop.
Javascript conversion of datetime strings in PHP pages to user's timezone
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$(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; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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