trying to make a simple countdown timer in PHP based on some input from a database which will tweak the end time slightly (with a constant base). However it seems to keep throwing up really strange numbers in the countdowns. I pretty much guarantee my math is wrong somewhere.
PHP
$timeUntil = 10; // for tweaking time remaining (days), this will be dynamic in actual program but will always be an integer
$timeStamp = 1445438099; // timestamp of roughly 2 months in the future
$zUnixDays = $timeUntil * 86400; // converting integer (days) into seconds
$zFinalTime = $timeStamp - $zUnixDays; //tweaking the constant time with the variable time
$remaining = $zFinalTime - time(); // seconds remaining from the future time til now
$seconds_remaining = $remaining%60;
$minutes_remaining = floor(($remaining%3600)/60);
$hours_remaining = floor(($remaining%86400)/3600);
$days_remaining = floor(($remaining%2592000)/86400);
$zTimeCombined = array($days_remaining, $hours_remaining, $minutes_remaining, $seconds_remaining);
echo json_encode($zTimeCombined);
JS
var result = JSON.parse(results);
var zDays = result[0];
var zHours = result[1];
var zMinutes = result[2];
var zSeconds = result[3];
this should return around 50 days remaining (2 months - 10 days.. very rough) but instead returns 21 days. Any ideas anyone?
Use DateTime instead, it's much easier:
$future = new DateTime();
$future->setTimestamp(1445438099); // passing in to constructor directly is wonky
$start = $future->sub(new DateInterval('P10D'));
$diff = $start->diff(new DateTime());
$interval = $diff->format('%y:%m:%d:%h:%i:%s');
// 0:1:20:23:29:45
list($year, $month, $day, $hour, $minute, $second) = explode(':', $interval);
<?php
$daysToFuture = 10;
// 10 Days in Future
$futureTs = mktime(0,0,0,date("n"),date("j")+$daysToFuture,date("Y"));
// remaining till now ...
$remaining = $futureTs-time();
// in Days
$days_remaining = date("d",$remaining);
echo "<pre>"; print_r($days_remaining); echo "</pre>";
// in hours
$hours_remaining = date("H",$remaining);
echo "<pre>"; print_r($hours_remaining); echo "</pre>";
// in minutes
$minutes_remaining = date("i",$remaining);
echo "<pre>"; print_r($minutes_remaining); echo "</pre>";
// in seconds
$seconds_remaining = date("s",$remaining);
echo "<pre>"; print_r($seconds_remaining); echo "</pre>";
// Array
$zTimeCombined = array($days_remaining, $hours_remaining, $minutes_remaining, $seconds_remaining);
echo "<pre>"; print_r($zTimeCombined); echo "</pre>";
I recommend you to use the DateTime and DateInterval objects
$dateTime = new DateTime();
$dateTime->setTimestamp(1445438099);
$timeInTheFuture = $dateTime->modify('-10 days');
$dateInterval = $timeInTheFuture->diff(new DateTime());
echo json_encode(explode(' ', $dateInterval->format('%d %h %i %s')));
Related
This question already has answers here:
Print time in 15-minute increments between two times in the same day
(10 answers)
Closed 11 months ago.
I'm trying to echo list of hours.
<?php
$startTime = "9:00:00";
$endTime = "19:00:00";
$st = strtotime($startTime);
$et = strtotime($endTime);
while ($st < $et) {
echo $st = date( "H:i", strtotime('+30 minutes', $st) );
echo '<br>';
}
?>
Inside that list, users will choose their reservation hour. But my while loop works like infinite loop.
Just like the previous answer, you're messing with data types while doing arithmetic.
PHP ships with built-in date time arithmetic through date and time API.
Your code could look much more clear and elegant and less error prone (no strtotime(), conversion, etc)
You could do something like this instead:
<?php
$startTime = DateTime::createFromFormat('H:i:s', '9:00:00');
$endTime = DateTimeImmutable::createFromFormat('H:i:s', '19:00:00');
$interval = new DateInterval('PT30M'); // 30 minutes
$reservation = [];
while ($startTime <= $endTime) {
$reservation[] = $startTime->format('H:i');
$startTime->add($interval);
}
echo join(PHP_EOL, $reservation) . PHP_EOL;
Links:
Date/Time Arithmetic
You're converting $st from a integer (timestamp) with strtotime() to a string with date() so your loop keeps going since while (string < integer)... is always true.
You can do this instead:
while ($st < $et) {
$st += (30 * 60); // Add 30 minutes in seconds
echo date("H:i", $st);
echo '<br>';
}
I need to show the difference between two times in PHP I use strtotime() function to convert my times to integer but my problem is the result not matched what I expected
<?php
$hour1 = '12:00:00';
$hour2 = '9:00:00';
$avg = strtotime($hour1) - strtotime($hour2);
$result = date('h:i:s', $avg); // result = 06:30:00 what I expected is 3:00:00
But the difference is 3:00:00 how to calculate this?
You can create DateTime instances and use diff function to get the difference between 2 times. You can then format them in hours,minutes and seconds.
<?php
$hour1 = '12:00:00';
$hour2 = '09:00:00';
$o1 = new DateTime($hour1);
$o2 = new DateTime($hour2);
$diff = $o1->diff($o2,true); // to make the difference to be always positive.
echo $diff->format('%H:%I:%S');
Demo: https://3v4l.org/X41pv
You can do that:
$hour1 = '12:00:00';
$hour2 = date('h', strtotime('9:00:00'));
$avg= date('h:i:s', strtotime($hour1. ' - '.$hour2.' hours') );
echo $avg; //3:00:00
I have following code that add 2 days to a given date.
$myDate = 2018-07-28 11:00:00; // the date is picked from db
$penaltyDays = 2;
$date1 = new DateTime($myDate);
$date1->add(new DateInterval("P{$penaltyDays}D")); // add N days
$now = new DateTime();
$interval = $date1->diff($now); // get difference
$days = $interval->d; // difference in days
I want value of $days must be 0 after passing exactly 48 hours. If 3 days are passed the value of $days should be -1.
I will also appreciate if someone tell me efficient/proper way to get the result.
To make an efficient code according to your specification then I would rather use strtotime than DateTime.
This code checks if the current time is larger than the database time + two (or three) days in seconds.
$myDate = "2018-07-28 11:00:00";
$unix = strtotime($myDate);
if(time() > ($unix + 86400*3)){
$days = -1;
}else if(time() > ($unix + 86400*2)){
$days = 0;
}else{
$days = "something else";
}
Echo $days;
https://3v4l.org/d6Q15
i have two different break time
default break time
extra break time
here i want to sum of two times and display 12 hrs format
EX :
$default_time = "00:30";
$extra_time = "00:25";
my expected output : 00:55
but now display 01:00
this is my code
$default_time = $work_data->break_time;
$break_time = $work_data->extra_time;
$total_break = strtotime($default_time)+strtotime($break_time);
echo date("h:i",strtotime($total_break));
Here is the function you can calculate total time by passing the arguments to functions.
$hours, $min are supposed variable which is zero
$default_time = "00:30";
$break_time = "00:25";
function calculate_total_time() {
$i = 0;
foreach(func_get_args() as $time) {
sscanf($time, '%d:%d', $hour, $min);
$i += $hour * 60 + $min;
}
if( $h = floor($i / 60) ) {
$i %= 60;
}
return sprintf('%02d:%02d', $h, $i);
}
// use example
echo calculate_total_time($default_time, $break_time); # 00:55
There is one function call to strtotime function too much.
You should leave out the strtotime() call in the last line, as $total_break already is a UNIX timestamp:
$total_break = strtotime($default_time)+strtotime($break_time);
echo date("h:i",$total_break);
The problem is that you're trying to add too specific timestamps, but what you're trying to achieve is adding two durations. So you need to convert those timestamps into durations. For that you need a base, which in your case is 00:00.
$base = strtotime("00:00");
$default_time = $work_data->break_time;
$default_timestamp = strtotime($default_time);
$default_duration = $default_timestamp - $base; // Duration in seconds
$break_time = $work_data->extra_time;
$break_timestamp = strtotime($break_time);
$break_duration = $break_timestamp - $base; // Duration in seconds
$total_break = $default_duration + $break_duration; // 55 min in seconds
// If you want to calculate the timestamp 00:55, just add the base back to it
echo date("H:i", $base + $total_break);
Consider using standard DateTime and DateInterval classes. All you will need is to convert your second variable value to interval_spec format (see http://php.net/manual/en/dateinterval.construct.php for details):
$defaultTime = "00:30";
$breakTime = "PT00H25M"; // Or just 'PT25M'
$totalBreak = (new DateTime($defaultTime))->add($breakTime);
echo $totalBreak->format('H:i');
You could try the following code fragment:
$time1 = explode(":", $default_time);
$time2 = explode(":", $break_time);
$fulltime = ($time1[0] + $time2[0]) * 60 + $time1[1] + $time2[1];
echo (int)($fulltime / 60) . ":" . ($fulltime % 60);
<?php
$time = "00:30";
$time2 = "00:25";
$secs = strtotime($time2)-strtotime("00:00:00");
$result = date("H:i:s",strtotime($time)+$secs);
print_r($result);
?>
Use below code you will definitely get your answers.
$default_time = "00:30:00";
$extra_time = "00:25:00";
$secs = strtotime($extra_time)-strtotime("00:00:00");
$result = date("H:i:s A",strtotime($default_time)+$secs);
echo $result;die;
You can modify above code as per your need.
You could try the following:
$default_time = $work_data->break_time;
$date_start = new DateTime($default_time);
$break_time = $work_data->extra_time;
$interval = new DateInterval("PT" . str_replace(":", "H", $break_time) . "M");
$date_end = $date_start->add($interval);
echo $date_end->format("H:i");
Note that this doesn't account for times which span a 24 hour period
Hello I try to take the difference between two dates and display it.
My problem is that the time difference I get is not the correct one.
This is my code:
$time1 = strtotime('2014-03-28 15:20:00');
$time2 = strtotime('2014-03-28 15:15:00');
$diffTime = $time1 - $time2;
echo date('H:i', $diffTime);
The result I get is:
02:05
The currect time should be this:
00:05
My guess that the date somehow takes timezone or something like this but Im not sure.
Thanks.
/****************************************
$start_date = new DateTime('23:58:40'); *These two still give
$end_date = new DateTime('00:00:00'); *a wrong answer
*****************************************/
$start_date = new DateTime('23:58:40');
$end_date = new DateTime('00:11:36');
$dd = date_diff($end_date, $start_date);
//Giving a wrong answer: Hours = 23, Minutes = 47, Seconds = 4
echo "Hours = $dd->h, Minutes = $dd->i, Seconds = $dd->s";
So what you're actually doing here is generating two UNIX timestamps (numbers) and then subtracting them. then you're passing the resulting number as if it were still a timestamp to date().
essentially $diffTime is the number of seconds between your two times. you could divide by 60 to get minutes, and so on and so forth, but PHPs DateTime objects are much better.
From the PHP docs:
http://pl1.php.net/strtotime
Note:
Using this function for mathematical operations is not advisable. It is better to use DateTime::add() and DateTime::sub() in PHP 5.3 and later, or DateTime::modify() in PHP 5.2.
try this
<?php
$time1 = strtotime('2014-03-28 15:20:00');
$time2 = strtotime('2014-03-28 15:15:00');
echo round(abs($time1 - $time2) / 60,2). " minute"
?>
Below is the solution of date time in years,days.hours,minutes and seconds.
$time1 = strtotime('2014-03-28 15:20:00');
$time2 = strtotime('2014-03-28 15:15:00');
$diffTime = $time1 - $time2;
$y = ($diffTime/(60*60*24*365));
$d = ($diffTime/(60*60*24))%365;
$h = ($diffTime/(60*60))%24;
$m = ($diffTime/60)%60;
$s = ($diffTime)%60;
echo "Minutes - " .$m;
echo "<br/>";