I want to have a live countdown timer on my archive page/sliders where I count down the auction.
Currently using only PHP but this is not live ofcourse because I need to refresh the page. So I guess the best way would be javascript.
I currently have this code in my functions.php the years/months/days/ours work fine but seconds don't
`
function auction_end_date_countdown() {
global $product;
$product = apply_filters( 'yith_wcact_get_auction_product', $product );
ob_start();
if ( 'auction' === $product->get_type() ) {
$dateclose = $product->get_end_date();
if ( $dateclose ) {
$today = date("Y-m-d H:i:s");
$format_date = get_option( 'yith_wcact_general_date_format', 'Y-m-d H:i:s' );
$format = $format_date . ' ' . $format_time;
$date = ( date( 'Y-m-d H:i:s', $dateclose ) );
$diff = abs(strtotime($today) - strtotime($date));
$years = floor($diff / (365*60*60*24));
$months = floor(($diff - $years * 365*60*60*24) / (30*60*60*24));
$days = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24)/ (60*60*24));
$hours = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24 - $days*60*60*24)/ (60*60));
$minuts = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24 - $days*60*60*24 - $hours*60*60)/ 60);
$seconds = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24 - $days*60*60*24 - $hours*60*60 - $minuts*60));
if ($today < $date) {
printf("%d dagen, %d uren", $days, $hours);
echo $date;
// printf("%d maanden, %d dagen, %d uren", $months, $days, $hours);
}else{
echo 'Afgelopen';
}
}
}
$html = ob_get_clean();
return $html;
}
add_shortcode( 'veiling_eind_datum_aftellen', 'auction_end_date_countdown' );
`
I added the shortcode to my grid so each auction gets the ending time.
But now I am struggeling to implement a live times in to this.
I am trying to Show a Countdown Timer Inside Foreach loop for every record in PHP Codeigniter Framework, It is basically showing Datediff between current date and mysql database date value as how many days left, Below is my code.Problem is it is showing countdown timer for single record only not for every record i need
<?php foreach ($my_courses as $my_course):
$course_details = $this->crud_model->get_course_by_id($my_course['course_id'])->row_array();
<!-- countdown timer-->
<?php if ($course_details['is_onlineclass']==='Yes'): ?>
<span style="display:inline-block;font-size:12px;font-color:crimson;"><?php
$t=$course_details['live_class_schedule_time'];
//time difference in seconds for coundown timer
$date = new DateTime();
$date2 = new DateTime(date("yy-m-d h:i:s a", $t));
$diff = $date->getTimestamp() - $date2->getTimestamp() ;
echo $diff;
?></span>
<span id="<?echo $my_course['course_id']?>" class="timer" style="font-size:smaller;color:crimson;"></span>
<?php endif; ?>
<script>
var initialTime = <?echo $diff?>;
var seconds = initialTime;
function timer() {
var days = Math.floor(seconds/24/60/60);
var hoursLeft = Math.floor((seconds) - (days*86400));
var hours = Math.floor(hoursLeft/3600);
var minutesLeft = Math.floor((hoursLeft) - (hours*3600));
var minutes = Math.floor(minutesLeft/60);
var remainingSeconds = seconds % 60;
if (remainingSeconds < 10) {
remainingSeconds = "0" + remainingSeconds;
}
document.getElementById('<?echo $my_course['course_id']?>').innerHTML = days + "days " + hours + "hours " + minutes + "min " + remainingSeconds+ "sec left";
if (seconds == 0) {
learInterval(countdownTimer);
document.getElementById('<?echo $my_course['course_id']?>').innerHTML = "Completed";
} else {
seconds--;
}
}
var countdownTimer = setInterval('timer()', 1000);
</script>
What is the wrong I am doing and How to show the timer for every record
Your function name and call should also be unique.
EDIT
Also you messed up a log of code. I have commented the foreach loop and put my own for loop. Modify accordingly
Try this.
<?php
$my_course['course_id'] = 0;
for($i = 0; $i <= 2; $i++):
// foreach ($my_courses as $my_course):
// $course_details = $this->crud_model->get_course_by_id($my_course['course_id'])->row_array();
// You need to comment this out when you put your code live
$course_details['is_onlineclass'] = "Yes";
$course_details['live_class_schedule_time'] = time() + rand(0, 300);
$my_course['course_id'] += 1;
// remove till here
if ($course_details['is_onlineclass']==='Yes'):
?>
<span style="display:inline-block;font-size:12px;font-color:crimson;">
<?php
$t=$course_details['live_class_schedule_time'];
//time difference in seconds for coundown timer
$date = new DateTime();
$date2 = new DateTime(date("yy-m-d h:i:s a", $t));
$diff = $date->getTimestamp() - $date2->getTimestamp() ;
?>
</span>
<span id="<?php echo $my_course['course_id']; ?>" class="timer" style="font-size:smaller;color:crimson;"></span>
<?php endif; ?>
<script>
var initialTime = <?php echo $diff; ?>
var seconds = initialTime;
function timer<?php echo $my_course['course_id'];?>() {
var days = Math.floor(seconds/24/60/60);
var hoursLeft = Math.floor((seconds) - (days*86400));
var hours = Math.floor(hoursLeft/3600);
var minutesLeft = Math.floor((hoursLeft) - (hours*3600));
var minutes = Math.floor(minutesLeft/60);
var remainingSeconds = seconds % 60;
if (remainingSeconds < 10) {
remainingSeconds = "0" + remainingSeconds;
}
document.getElementById('<?php echo $my_course['course_id']?>').innerHTML = days + "days " + hours + "hours " + minutes + "min " + remainingSeconds+ "sec left";
if (seconds == 0) {
learInterval(countdownTimer);
document.getElementById('<?php echo $my_course['course_id']?>').innerHTML = "Completed";
} else {
seconds--;
}
}
var countdownTimer = setInterval('timer<?php echo $my_course["course_id"];?>()', 1000);
</script>
<?php endfor; ?>
EDIT: Here is your code
<?php
foreach ($my_courses as $my_course):
$course_details = $this->crud_model->get_course_by_id($my_course['course_id'])->row_array();
if ($course_details['is_onlineclass']==='Yes'):
?>
<span style="display:inline-block;font-size:12px;font-color:crimson;">
<?php
$t=$course_details['live_class_schedule_time'];
//time difference in seconds for coundown timer
$date = new DateTime();
$date2 = new DateTime(date("yy-m-d h:i:s a", $t));
$diff = $date->getTimestamp() - $date2->getTimestamp() ;
?>
</span>
<span id="<?php echo $my_course['course_id']; ?>" class="timer" style="font-size:smaller;color:crimson;"></span>
<?php endif; ?>
<script>
var initialTime = <?php echo $diff; ?>
var seconds = initialTime;
function timer<?php echo $my_course['course_id'];?>() {
var days = Math.floor(seconds/24/60/60);
var hoursLeft = Math.floor((seconds) - (days*86400));
var hours = Math.floor(hoursLeft/3600);
var minutesLeft = Math.floor((hoursLeft) - (hours*3600));
var minutes = Math.floor(minutesLeft/60);
var remainingSeconds = seconds % 60;
if (remainingSeconds < 10) {
remainingSeconds = "0" + remainingSeconds;
}
document.getElementById('<?php echo $my_course['course_id']?>').innerHTML = days + "days " + hours + "hours " + minutes + "min " + remainingSeconds+ "sec left";
if (seconds == 0) {
learInterval(countdownTimer);
document.getElementById('<?php echo $my_course['course_id']?>').innerHTML = "Completed";
} else {
seconds--;
}
}
var countdownTimer = setInterval('timer<?php echo $my_course["course_id"];?>()', 1000);
</script>
<?php endforeach; ?>
I am currently stuck on a problem and not sure how to solve it. I am new to php and javascript coding so do please correct me if there is an easier way to do this.
My problem is that I am trying to get a countdown timer working for multiple data in mysql database. I have already made a successful countdown time function that only works with one data using the if statement in php, but when I try to do it with multiple data using the while statement in php it doesn't work.here is my php code
//TODAY'S DATE
$today = time();
//FETCHES DATE AND TIME FOR THE EVENT FROM DATABASE
$sql = "SELECT * FROM post";
$result = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_assoc($result)) {
$title = $row['title'];
$cname = $row['cname'];
$team = $row['team'];
$description = $row['description'];
$endtime = $row['endtime'];
echo "<tr>";
echo "<td width='16%'><strong>Title:</strong></td>";
echo "<td width='16%'>$title</td>";
echo "</tr><tr>";
echo "<td width='16%'><strong>Client name:</strong></td>";
echo "<td width='16%'>$cname</td>";
echo "</tr><tr>";
echo "<td width='16%'><strong>Team:</strong></td>";
echo "<td width='16%'>$team</td>";
echo "</tr><tr>";
echo "<td width='16%'><strong>Description:</strong></td>";
echo "<td width='16%'>$description</td>";
echo "</tr><tr>";
echo "<td width='16%'><strong>End time:</strong></td>";
echo "<td width='16%'>$endtime</td>";
echo "</tr><tr>";
echo"</BR>";
echo"</BR>";
}
$conn->close();
below is my javascript that suppose to run the count down
<script language="JavaScript">
var today = new Date();
var DD = today.getDate();
var MM = today.getMonth()+1; //January is 0!
var YYYY = today.getFullYear();
//let get the Difference in Sec btw the two dates
var _DateFromDBProgEndDate = '<?php echo $endtime; ?>';
var ProgEndTime = new Date(_DateFromDBProgEndDate);
var TodayTime = new Date();
var differenceTravel = ProgEndTime.getTime()- TodayTime.getTime() ;
var seconds = Math.floor((differenceTravel) / (1000));
////////////////////////////////
var SecDiffFromToday = seconds;
var seconds = SecDiffFromToday;
function pad(n) {
// utility function to pad a number to 2 digits:
return ('0' + n).substr(-2);
}
function timer() {
var todaySeconds = Math.floor(new Date().getTime() / 1000);
// collect the html first in an array
var html = [];
// keep track whether there are still counters not yet zero:
var allDone = true;
// go through the list of dates:
endDatesInSeconds.forEach(function (endDateSeconds) {
var totalSeconds = endDateSeconds - todaySeconds;
var days = Math.floor(totalSeconds/24/60/60);
var seconds = Math.floor(totalSeconds - days*86400);
var hours = Math.floor(seconds/3600);
seconds = Math.floor(seconds - hours*3600);
var minutes = Math.floor(seconds/60);
seconds = seconds % 60;
// add a part of html
html.push(
totalSeconds <= 0
? 'project time Completed'
: days + ":" + pad(hours) + ":" + pad(minutes) + ":" + pad(seconds));
// when at least one counter is not complete, we are not done:
allDone = allDone && totalSeconds <= 0;
});
// now put the html in the document:
document.getElementById('countdown').innerHTML = html.join('<br/>');
if (allDone) {
clearInterval(countdownTimer);
}
}
var countdownTimer = setInterval('timer()', 1000);
</script>
the javascript run the countdown by getting it value from the php (var _DateFromDBProgEndDate = '<?php echo $endtime; ?>';)
I have looked at all the examples and I can't figure out why FullCalendar won't show the proper time for my events. For each event it just lists 12a instead of the actual time. Can someone please take a look at my code below and let me know what I am doing wrong.
JavaScript
jQuery('#calendar').fullCalendar({
allDayDefault: false,
disableDragging: true,
eventSources: [{
events: function(start, end, callback) {
var month = end.getMonth();
month = ('0' +month).slice(-2)
if(month == '0')
{
var year = start.getFullYear(); month = '12';
}
else
var year = end.getFullYear();
var new_url = "<?php echo get_bloginfo('siteurl').'/json-events.php?month='; ?>" + month + "&year="+year;
if( new_url != current_url ){
jQuery.ajax({
url: new_url,
dataType: 'json',
type: 'POST',
success: function( response ) {
current_url = new_url;
user_events = response;
callback(response);
}
});
}else{
callback(user_events);
}
}
}],
theme: true,
header: {
left: 'prev,next',
center: 'title',
right: ''
},
editable: true,
eventRender: function(event, element) {
element.qtip({
content: event.description
});
},
.
PHP
require_once("includes/classService.php");
$classService = new MBClassService();
require_once("includes/clientService.php");
$classClient = new MBClientService();
session_start();
function cmp($a, $b) {
$expA = explode('T',$a->StartDateTime);
$startTimesA = strtotime($expA[1]).' ';
$expB = explode('T',$b->StartDateTime);
$startTimesB = strtotime($expB[1]);
return (strcmp ($startTimesA,$startTimesB));
}
$time = '';
$currentYr = $_GET['year'];
$currentDy = '01';
$currentMonth = $_GET['month'];
$k = 0;
$startDate = $currentYr.'-'.$currentMonth.'-'.$currentDy;
$lastDay = date('t',strtotime($startDate));
$endofDate = $currentYr.'-'.$currentMonth.'-'.$lastDay;
$recordOfClientAddClass = $classClient->GetClientSchedule($_SESSION['ClientId'],$startDate,$endofDate);
$bookClassArray = array();
for($k = 0; $k < count($recordOfClientAddClass); $k++) {
$bookClassArray[] = $recordOfClientAddClass[$k]->ClassID;
}
for( $j = 1; $j <= $lastDay; $j++ ) {
$days = sprintf("%02s", $j);
$months = sprintf("%02s", $currentMonth);
$currentYr = date('Y');
$start = $currentYr.'-'.$months.'-'.$days.' 00:00:00';
$ends = $currentYr.'-'.$months.'-'.$days.' 23:59:59';
$classesList = $classService->GetClasses(array(), array(), array(), array(), $ends, $ends);
//echo "<pre>"; print_r($classesList);
if(!empty($classesList[0])) {
uasort($classesList, 'cmp');
$classesList = array_values($classesList);
for($k = 0; $k < count($classesList); $k++ ) {
$exp = explode('T',$classesList[$k]->StartDateTime);
$startDateOfClass = $exp[0];
$startTime = $exp[1];
$reformatted_stime = date('g:i a',strtotime($startTime));
$endTime = end(explode('T',$classesList[$k]->EndDateTime));
$t1 = strtotime($startTime);
$t2 = strtotime($endTime);
$delta_T = ($t2 - $t1);
$hours = round((($delta_T % 604800) % 86400) / 3600, 2);
$minutes = round(((($delta_T % 604800) % 86400) % 3600) / 60, 2);
$seconds = round((((($delta_T % 604800) % 86400) % 3600) % 60), 2);
if($hours)
$time .= $hours ." hour " ;
if($minutes)
$time .= $minutes ." Minutes " ;
if($seconds)
$time .= $seconds ." Second " ;
$reformatted_etime = date('g:i a',strtotime($endTime));
if(time() < strtotime($startDateOfClass) && !in_array($classesList[$k]->ID,$bookClassArray))
$url = $classesList[$k]->ID."&".$startDateOfClass."";
else
$url = "";
if(in_array($classesList[$k]->ID,$bookClassArray))
$register = "Already Registered!";
else
$register = "";
$description = '';
if($register != "")
$description .= '<strong style="color:#64C063;">'.$register.'</strong><br>';
$description .= '<strong>Class Name:</strong> '.$classesList[$k]->ClassDescription->Name.'<br> <strong>Teacher:</strong> '.$classesList[$k]->Staff->Name.'<br> <strong>Duration:</strong> '.$time.
'<br> <strong>Time:</strong> '.$reformatted_stime.' To ' .$reformatted_etime."";
if($url) {
$jsonFirstArry[] = array(
'title' => $classesList[$k]->ClassDescription->Name,
'start' => "$currentYr-$months-$days",
'url' => $url,
'className' => 'clickTip',
'description' => "$description"
);
} else {
$jsonFirstArry[] = array(
'title' => $classesList[$k]->ClassDescription->Name,
'start' => "$currentYr-$months-$days",
'className' => 'clickTip',
'description' => "$description"
);
}
$time = '';
}
}
}
echo json_encode($jsonFirstArry);
?>
.
Thanks!
That's the default time format for FullCalendar. You'll want to look at the timeFormat documentation for details on how to implement a change to it, and the formatDate documentation for specifics on how the time formats work.
As both an example and a quick fix to your specific problem, if you were to specify...
timeFormat: 'h:mmtt'
...in your calendar object, at the same level where you specify your event sources and theme, that should display the full "am" or "pm". Under this formatting, 7pm would display "7:00pm".
i have opencart module daily deal, but the countdown timer is not working.
function code:
<?php
class ModelCatalogSpecialPriceCountDown extends Model {
public function getProductSpecialDates($product_id) {
(string) $display_output = null;
(string) $minute = 60;
(string) $hour = 60 * $minute;
(string) $day = 24 * $hour;
if ($this->customer->isLogged()) {
$customer_group_id = $this->customer->getCustomerGroupId();
} else {
$customer_group_id = $this->config->get('config_customer_group_id');
}
$query = $this->db->query("SELECT date_start, date_end FROM " . DB_PREFIX . "product_special WHERE product_id = '" . (int)$product_id . "' AND customer_group_id = '" . (int)$customer_group_id . "' AND ((date_start = '0000-00-00' OR date_start < NOW()) AND (date_end = '0000-00-00' OR date_end > NOW())) ORDER BY priority ASC, price ASC LIMIT 1");
if ($query->num_rows) {
$time_left = strtotime($query->row["date_end"]) - strtotime(date('Y-m-d'));
$days_left = floor($time_left/$day);
if ($time_left > 0)
{
$display_output = getdate();
$display_output["days_left"] = $days_left;
}
}
return $display_output;
}
}
?>
and the code using it:
<!-- Countdown start -->
<div id="defaultCountdown<?php echo $product['product_id'];?>" class="countdown_dashboard"></div>
<script type="text/javascript"><!--
$(document).ready(function() {
$('#defaultCountdown<?php echo $product["product_id"]; ?>').countdown({
until: new Date(<?php echo $product['yleft'];?>, <?php echo $product['mleft'];?> - 1, <?php echo $product['dleft'];?>)
});
});
//-->
</script>
My countdown doesn't work, the numbers change only when I refresh the page.