Pretty simple concept. My version supports multiple timers on a single page, also.
Probably not the nicest way, as it's writing to the DOM in 2 places (to update the data attribute and to display the time left), but hey. Free code is free code.
Grab the timestamp
Format the data attributes (the date difference as a string)
Create the div
Javascript calculations
<?php
$intCurrentTime = time();
$arrTimes = array(
1449652661, //45 seconds ago
1449652106, //10 minutes ago
1449649106 //1 hour ago
);
$objCurrentTime = new \DateTime(null, new \DateTimeZone("Europe/London"));
$objCurrentTime->setTimestamp($intCurrentTime);
foreach($arrTimes as $intTimestamp) {
$objOldTime = new \DateTime(null, new \DateTimeZone("Europe/London"));
$objOldTime->setTimestamp($intTimestamp);
$objDifference = $objCurrentTime->diff($objOldTime);
echo "<div class=\"time_diff\" data-timestamp=\"". $intTimestamp ."\" data-time_str=\"". $objDifference->format("%yy %mm %dd %hh %im %ss") . "\"></div> <br />";
}
?>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready( function() {
setInterval( function() {
$(".time_diff").each( function() {
var strTime = $(this).data('time_str');
var intTimestamp = $(this).data('timestamp');
var arrLabel = [];
var arrDateDiff = strTime.match(/^(\d{1,2})\w\s(\d{1,2})\w\s(\d{1,2})\w\s(\d{1,2})\w\s(\d{1,2})\w\s(\d{1,2})\w$/);
var intYear = arrDateDiff[1];
var intMonth = arrDateDiff[2];
var intDays = arrDateDiff[3];
var intHours = arrDateDiff[4]
var intMinutes = arrDateDiff[5];
var intSeconds = arrDateDiff[6];
intSeconds = intSeconds - 1;
if( intSeconds <= 0 ) {
intSeconds = 0;
if( intMinutes > 0) {
intSeconds = 60;
--intMinutes;
}
}
if( intMinutes <= 0 ) {
intMinutes = 0;
if( intHours > 0 ) {
intMinutes = 59;
--intHours;
}
}
if( intHours <= 0 ) {
intHours = 0;
if( intDays > 0 ) {
intHours = 60;
--intDays;
}
}
if( intDays <= 0 ) {
intDays = 0;
if( intMonth > 0 ) {
intDays = 30; //roughly. shhhh
--intMonth;
}
}
if( intMonth <= 0 ) {
intMonth = 0;
if( intYear > 0 ) {
intYear = 1;
}
}
if( intSeconds > 0 ) {
arrLabel.push(intSeconds + " seconds ");
}
if( intMinutes > 0 ) {
arrLabel.push(intMinutes + " minutes");
}
if( intHours > 0 ) {
arrLabel.push(intHours + " hours");
}
if( intDays > 0 ) {
arrLabel.push(intDays + " days");
}
if( intMonth > 0 ) {
arrLabel.push(intMonth + " months");
}
if( intYear > 0 ) {
arrLabel.push(intYear + " years");
}
arrLabel.reverse();
$(this).html(arrLabel.join(" "));
$(this).data("time_str", intYear + 'y ' + intMonth + 'm ' + intDays + 'd ' + intHours + 'h ' + intMinutes + 'm ' + intSeconds + 's');
})
}, 1000);
});
</script>