Last active
December 20, 2015 04:59
-
-
Save windix/6075388 to your computer and use it in GitHub Desktop.
timestamp handling example for PHP and javascript
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
<?php | |
$now = time(); | |
?> | |
<html> | |
<head> | |
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></script> | |
<script type="text/javascript"> | |
// we will add our javascript code here | |
function format_time(d) { | |
// 24-hour format of an hour with leading zeros | |
var h = new String(d.getHours()).length == 1 ? "0" + d.getHours() : d.getHours(); | |
// Minutes with leading zeros | |
var m = new String(d.getMinutes()).length == 1 ? "0" + d.getMinutes() : d.getMinutes(); | |
return h + ":" + m; | |
} | |
// Offset is in second, GMT+10 will be 36,000 | |
function convert_ts_to_local_date(ts, offset) { | |
var GMT_offset = new Date().getTimezoneOffset() * -60; | |
return new Date((ts - GMT_offset + offset) * 1000); | |
} | |
$(document).ready(function() { | |
var ts = <?= $now ?>; | |
var d = new Date(ts * 1000); | |
var s = ""; | |
s += d.getTimezoneOffset() + "<br />"; | |
s += d.getTime() + "<br />"; | |
s += format_time(d) + "<br />"; | |
var customer_offset = 9.5 * 3600; // second: GMT+10 -> 36,000 | |
var d1 = convert_ts_to_local_date(ts, customer_offset); | |
s += format_time(d1) + "<br />"; | |
$("#content").html(s); | |
}); | |
</script> | |
</head> | |
<body> | |
<pre> | |
<?php | |
/* Time stamp is the seconds since 1970-1-1 00:00:00 GMT, | |
* so it is not changed along with time zone | |
* | |
* When time zone change, the local time parsed from time stamp changes | |
* | |
* On java script side, we cannot control the timezone. Instead, | |
* we can manipulate the time stamp to make it looks like that the time zone | |
* has been changed, but actually we always stay in the same time zone. | |
* | |
*/ | |
get_ts_info($now); | |
date_default_timezone_set('Australia/Darwin'); | |
get_ts_info($now); | |
date_default_timezone_set('GMT'); | |
get_ts_info($now); | |
function get_ts_info($ts) { | |
echo date_default_timezone_get()."\n"; | |
echo date('Y-m-d H:i:s', $ts)."\n"; | |
echo $ts."\n"; | |
} | |
?> | |
</pre> | |
<!-- we will add our HTML content here --> | |
JS output:<br /> | |
<p id="content"></p> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment