Woocommerce auction live countdown archive - javascript

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.

Related

i have booked dates in calendarm i want to show info from datesbase on the dates

* In javascript part i got the dates that are booked by user on dates, i n calendar i marked that dates are unavilable, but i want to show user info on that dates
<script type="text/javascript">
// Add New Dates and Block Out Booked Days Below
/*var unavailableDates1 = ["20-5-2016", "21-5-2016", "22-5-2016", "23-5-2016", "5-6-2016", "7-6-2016", "8-6-2016",
"15-6-2016", "16-6-2016", "25-6-2016", "26-6-2016", "27-6-2016", "28-6-2016", "14-2-2016",
"15-7-2016", "16-7-2016", "17-7-2016", "18-7-2016", "19-7-2016","20-7-2016","21-7-2016",
]; */
var unavailableDates = <?php echo json_encode($arr2); ?>;
var unavaila = <?php echo json_encode($e); ?>;
document.write(unavailableDates);
function unavailable(date) {
dmy = date.getDate() + "-" + (date.getMonth() + 1 ) + "-" + date.getFullYear();
if($.inArray(dmy, unavailableDates) == -1) {
return [true, ""];
}else {
return [false, "", unavaila];
}
}
$(function() {
$("#Datepicker1").datepicker({
numberOfMonths:3,
beforeShowDay: unavailable
});
});
</script>
*
and my php code is getting the dates from database in between start to end m, and showing calendar booked, how to show info on that
<?php
include 'dbconfig.php';
$query_getaway = "SELECT * FROM getaway_table; ";
$result_getaway = $db->query($query_getaway);
$category = mysqli_real_escape_string($db, filter_input(INPUT_POST, 'category')) .'<br>';
$resort = mysqli_real_escape_string($db, filter_input(INPUT_POST, 'resorts')) .'<br>';
if( $category != 0 ){
$query = "SELECT * FROM booking_request where room_id = '$resort' '<br>' ";
$result = $db->query($query);
if( $result -> num_rows > 0 ) {
while( $row = $result-> fetch_assoc() )
{
$name = $row['getaway_name']." <br>";
$start = $row['check_in_date']." <br>";
$end = $row['check_out_date']." <br>";
$guest_n[]= $row['guest_name'];
$guest_number[]= $row['guest_phone'];
$arr1 = range(strtotime($row['check_in_date']),strtotime($row['check_out_date']), "86400");
array_walk_recursive($arr1, function(&$element) { $element = date("j-n-Y", $element); });
foreach ($arr1 as $value)
{
$arr2[]= $value;
}
$arrt= (array_merge($guest_n, $guest_number));
//print_r($arrt);
foreach($arrt as $val)
{
echo $arr_val[]=$val;
}
$arr[]= $value;
}
}
else { echo "select" ;}
?>
how to get the result to show user details on mousehover on dates from db.

FullCalendar doesn't display the proper time

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".

Showing a 'Now Playing' in HTML and PHP

I have been trying to use some PHP and HTML code (with a bit of js) to create a 'now playing' spotify viewer for my website. I just cannot get it working. I have tried all the possibilities such as renaming files, changing the HTML and PHP and JS versions but nothing seems to work. Below is my HTML code (js) and PHP code.
<script src="jquery-1.11.0.min.js"></script>
<!--Begin Spotify Scrobble-->
<SCRIPT TYPE="text/javascript">function get_spotify() {
$.ajax({
type: 'POST',
url: '/public_html/Spotify.php',
data: { request: 'true' },
success: function(reply) {
$('.now-playing').html("<p>" + reply + "</p>");
}
});
}
</script>
<!--End Spotify Scrobble-->
PHP
?php
// Account & API Account Information
$user = "USERNAME"; // <---- Your username goes here
$key = "KEY"; //<-- Your API key goes here
+
// The URL of the request to API Service
$url = "http://ws.audioscrobbler.com/2.0/? method=user.getrecenttracks&user=USERNAME&api_key=APIKEY&forma t=json";
+
// Enable Shortening
$short_titles = false;
+
// Setup cURL for request
$ch = curl_init( $url );
-// Options for cURL
$options = array(
CURLOPT_RETURNTRANSFER => true
);
curl_setopt_array($ch, $options);
-// Execute cURL and save return to $json
+
+// Execute cURL
$json = curl_exec($ch);
-// Close the connection
curl_close($ch);
-// Decode JSON response to array.
$data = json_decode($json,true);
+
// Get only the latest track information
$last = $data['recenttracks']['track'][0];
+
// Is now playing attribute present?
if (isset($last['#attr']['nowplaying'])) {
- // Echo now playing information.
+
$output = "I am currently listening to " . $last['name'] . ' by ' . $last['artist']['#text'] . " on Spotify.";
+
if ($short_titles) {
$output = sTrim($output);
}
+
echo trim($output);
} else {
- // Collect info on when this was last played and get the current UNIX time.
$played = $last['date']['uts']; $now = time();
- // Get the difference
$diff = abs($now - $played);
- // format hours
+
+ // Time formatting
$hours = intval(intval($diff) / 3600);
- // format minutes
$minutes = intval(($diff / 60) % 60);
- // IF hours is empty(equal to zero)
+
+ // String formatting based on time
if (!empty($hours)) {
- if ($hours > 24) // Is it more than 1 day?
+ if ($hours > 24)
$time = "over a day ago";
else
$time = $hours . " hours and " . $minutes . " minutes ago";
} else
$time = $minutes . " minutes ago";
+
$output = "I last listened to " . $last['name'] . ' by ' . $last['artist'] ['#text'] . " $time on Spotify";
+
if ($short_titles) {
$output = sTrim($output);
}
+
echo trim($output);
}
+
exit();
function sTrim($output) {

Javascript countdown only when page reload

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.

Getting datetime from mysql into php?

I have the following code (a countdown timer using php and javascript) that I am working on. What I am trying to do is to get the datetime ($end_date) from the mysql and place it in the $date ='' inside my code.
This code will work just fine if i enter the date and time manually in the code like this: $date = 'September 17 2013 12:00:00 PM GMT';
but i need it to work some how like this:
$date = echo $dynamicList;
or like this maybe:
$date = echo $end_date;
I'm not sure what I am doing wrong!
here is my full code:
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
?>
<?php date_default_timezone_set('GMT'); ?>
<?php
session_start();
// Run a select query to get my letest 6 items
// Connect to the MySQL database
include "config/connect.php";
$dynamicList = "";
$sql = "SELECT * FROM item ORDER BY id";
$query = mysqli_query($db_conx, $sql);
$productCount = mysqli_num_rows($query); // count the output amount
if ($productCount > 0) {
while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)){
$id = $row["id"];
$product_name = $row["product_name"];
$date_added = strftime("Y-m-d", strtotime($row["date_added"]));
$end_date = strftime("Y-m-d H:i:s", strtotime($row["end_date"]));
$price = $row["price"];
$dynamicList .= '<div>' . $end_date . '
</div>';
}
} else {
$dynamicList = "No Records";
}
?>
<?php
$date = echo $dynamicList;
$exp_date = strtotime($date);
$now = time();
if ($now < $exp_date) {
?>
<script>
// Count down milliseconds = server_end - server_now = client_end - client_now
var server_end = <?php echo $exp_date; ?> * 1000;
var server_now = <?php echo time(); ?> * 1000;
var client_now = new Date().getTime();
var end = server_end - server_now + client_now; // this is the real end time
var _second = 1000;
var _minute = _second * 60;
var _hour = _minute * 60;
var _day = _hour *24
var timer;
function showRemaining()
{
var now = new Date();
var distance = end - now;
if (distance < 0 ) {
clearInterval( timer );
document.getElementById('countdown').innerHTML = 'EXPIRED!';
return;
}
var days = Math.floor(distance / _day);
var hours = Math.floor( (distance % _day ) / _hour );
var minutes = Math.floor( (distance % _hour) / _minute );
var seconds = Math.floor( (distance % _minute) / _second );
var countdown = document.getElementById('countdown');
countdown.innerHTML = '';
if (days) {
countdown.innerHTML += 'Days: ' + days + '<br />';
}
countdown.innerHTML += 'Hours: ' + hours+ '<br />';
countdown.innerHTML += 'Minutes: ' + minutes+ '<br />';
countdown.innerHTML += 'Seconds: ' + seconds+ '<br />';
}
timer = setInterval(showRemaining, 1000);
</script>
<?php
} else {
echo "Times Up";
}
?>
<div id="countdown"></div>
could someone please help me out with this?
I do not get any errors on my page. only a blank page and if I change $date = echo $dynamicList; to $date = '$dynamicList'; i get the Times Up message!
any help would be appreciated.
EDIT My new code:
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
?>
<?php date_default_timezone_set('GMT'); ?>
<?php
session_start();
// Run a select query to get my letest 6 items
// Connect to the MySQL database
include "config/connect.php";
$dynamicList = "";
$sql = "SELECT * FROM item ORDER BY id";
$query = mysqli_query($db_conx, $sql);
$productCount = mysqli_num_rows($query); // count the output amount
if ($productCount > 0) {
while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)){
$id = $row["id"];
$product_name = $row["product_name"];
$date_added = strftime("%Y-%m-%d", strtotime($row["date_added"]));
$end_date = strftime("%Y-%m-%d %H:%M:%S", strtotime($row["end_date"]));
$price = $row["price"];
$dynamicList .= '<div>' . $end_date . '
</div>';
}
} else {
$dynamicList = "No Records";
}
?>
<?php
$date = "'".$end_date."'";
$exp_date = strtotime($date);
$now = time();
if ($now < $exp_date) {
?>
<script>
// Count down milliseconds = server_end - server_now = client_end - client_now
var server_end = <?php echo $exp_date; ?> * 1000;
var server_now = <?php echo time(); ?> * 1000;
var client_now = new Date().getTime();
var end = server_end - server_now + client_now; // this is the real end time
var _second = 1000;
var _minute = _second * 60;
var _hour = _minute * 60;
var _day = _hour *24
var timer;
function showRemaining()
{
var now = new Date();
var distance = end - now;
if (distance < 0 ) {
clearInterval( timer );
document.getElementById('countdown').innerHTML = 'EXPIRED!';
return;
}
var days = Math.floor(distance / _day);
var hours = Math.floor( (distance % _day ) / _hour );
var minutes = Math.floor( (distance % _hour) / _minute );
var seconds = Math.floor( (distance % _minute) / _second );
var countdown = document.getElementById('countdown');
countdown.innerHTML = '';
if (days) {
countdown.innerHTML += 'Days: ' + days + '<br />';
}
countdown.innerHTML += 'Hours: ' + hours+ '<br />';
countdown.innerHTML += 'Minutes: ' + minutes+ '<br />';
countdown.innerHTML += 'Seconds: ' + seconds+ '<br />';
}
timer = setInterval(showRemaining, 1000);
</script>
<?php
} else {
echo "Times Up";
}
?>
<div id="countdown"></div>
Change these lines:
$date = echo $dynamicList;
With the following code:
$date = "'".$end_date."'";
And define the $end_date as a global variable.
And also add the some more parameter in the following for timezone:
$end_date = strftime("Y-m-d H:i:s A T", strtotime($row["end_date"]));
^^^ add these
You are getting the timesup message because of your if condition is not correct:
if ($now < $exp_date) {
As you are comparing the unixtimestap with the timeformat.
Use this code:
$date = "'".$end_date."'";
$exp_date = strtotime($date);
$now = strtotime(date("Y-m-d H:i:s A T"));
Then compare these time. You need to change the $now also.

Categories

Resources