0

I am using PHP to create a countdown functionality. It does work well given the limitation of the server side countdowns but the format is different from what I want to achieve.

I use the following code to achieve that:

<?php
date_default_timezone_set('Europe/London');
$date = strtotime("November 22, 2017 12:01 AM");
$remaining = $date - time();

if ($remaining > 0) {
    $days_remaining = floor($remaining / 86400);
    $hours_remaining = floor(($remaining % 86400) / 3600);
    $minutes_remaining = floor(($remaining % 3600) / 60);
}
?>

And output it using:

<div class="category-countdown">
    <? if ($remaining > 0) { ?>

    <div class="category-countdown--left">{{end-day}}</div>
    <div class="category-countdown--right">
      <div class="category-countdown__timer">
              <?= $days_remaining ?> : <?= $hours_remaining ?> : <?= $minutes_remaining ?>
      </div>
      <div class="category-countdown__annotation">days : hours : minutes</div>
    </div>
    <? } ?>
</div>

The current format is : 1 (day) : 3(hours) : 5(minutes)

What I want to achieve is : 01 (day) : 03(hours) : 05(minutes)

Can you help me?

Bluetree
  • 1,324
  • 2
  • 8
  • 25
John
  • 627
  • 6
  • 19

2 Answers2

2

You can use str_pad() like this,

str_pad($var, 2,'0',STR_PAD_LEFT);

Apply this in:

   $days_remaining  = str_pad(floor($remaining / 86400), 2,'0',STR_PAD_LEFT);
   $hours_remaining     = str_pad(floor(($remaining % 86400) / 3600), 2,'0',STR_PAD_LEFT);
   $minutes_remaining   = str_pad(floor(($remaining % 3600) / 60), 2,'0',STR_PAD_LEFT);
Bluetree
  • 1,324
  • 2
  • 8
  • 25
LF00
  • 27,015
  • 29
  • 156
  • 295
1
if ($remaining > 0) {
$days_remaining = floor($remaining / 86400);
$days_remaining = sprintf('%02d', $days_remaining);
$hours_remaining = sprintf('%02d', floor(($remaining % 86400) / 3600));
$minutes_remaining = sprintf('%02d', floor(($remaining % 3600) / 60));

}

yash
  • 29
  • 4