问题
I'm trying to make a relative countdown timer for the day (user input - defaults 8am to 6pm):
$mb_time_start = strtotime( 'today 0800' );
$mb_time_end = strtotime( 'today 1800' );
$mb_time_elapsed = ( $mb_time_end - $mb_time_start );
function mb_countdown_timer() {
var mb_time_start = <?= $mb_time_start; ?>,
mb_time_end = <?= $mb_time_end; ?>,
mb_time_now = new Date(),
mb_time_today = <?= $mb_time_end; ?>,
mb_time_elapsed = mb_time_now - mb_time_start,
mb_percent = ( ( mb_time_elapsed / mb_time_today ) );
console.log( mb_percent );
}
However at the moment the log is coming up as 998.9775919881246
which is incorrect - even for 7pm while writing this.
My intention after I can get the above is to have the calculation of 30 minute intervals between start
to end
-> 0800 to 1800 = 10h * 2 = 20
8am 12pm 6pm
-------------------------------------------------------------
| | | | | | | | | | | | | | | | | | | | |
-------------------------------------------------------------
Then from mb_countdown_timer()
fill the progress bar:
8am 12pm 6pm
------------------------------------------------------------------
| * | * | * | * | * | | | | | | | | | | | | | | | |
------------------------------------------------------------------
Any help would be appreciated!
回答1:
I am not sure if mb_percent = ( ( mb_time_elapsed / mb_time_today ) ); is correct. Shouldn't mb_time_today be equal to mb_time_end- mb_start
回答2:
First off, needed to set the timezone - that was issue one! Secondly, I misinterpreted the JS vs PHP outputs, which resulted in the JS being in milliseconds while PHP was seconds - so had to convert milliseconds to seconds. For the seconds part I had the question here: How would you loop every 30 minutes where I outputted the timer bar on top.
date_default_timezone_set( get_option('timezone_string') ); // Australia/Melbourne`
$mb_time_start = strtotime( 'today 0800' );
$mb_time_end = strtotime( 'today 1800' );
$mb_time_total = ( $mb_time_end - $mb_time_start ); // 36000
function mb_countdown_timer() {
// get the start time
var mb_time_start = <?= $mb_time_start; ?>,
// get the end time
mb_time_end = <?= $mb_time_end; ?>,
// get the seconds total (end - start)
mb_time_total = <?= $mb_time_total; ?>,
// get the time now
mb_time_now = new Date(),
// milliseconds to seconds
mb_time_now = Math.floor( mb_time_now / 1000 ),
// elapsed time from start time
mb_time_elapsed = mb_time_now - mb_time_start,
// convert to percentage
mb_time_percent = ( ( mb_time_elapsed / mb_time_total ) * 100 ),
// check the % is neither >100 or <0
mb_time_percent = ( (mb_time_percent > 100 || mb_time_percent < 0) ? 0 : mb_time_percent );
// add the positioning via css
$(".mb-marker").css("left", mb_time_percent + "%");
// run at 1 minute
setTimeout(mb_countdown_timer, 1000 * 60);
}
// run continuously
setInterval( mb_countdown_timer(), (1000 * 60) );
来源:https://stackoverflow.com/questions/59598158/how-would-you-make-a-countdown-timer-progress-bar-based-on-relative-times