php/mysql timer that use countdown from database - php

please I need help with counter (timer) that use table data as minutes to count. For example, i table i have row that sets number 5 (it will always be in minutes) and on php page i have table with some rows. i need to create on every row Start/End button. Clinking on Start will user value from table and start counting 5:00, 4:59 etc. Problem is that timer should not reset after refresh page (many people will look at this page).
I have this script that calculates start time and end time, but it will reset after refresh.
I did not post while table with rows, I did not think it is necessary.
in table, output of column that contain minutes is
<?php echo $row['Trajanje_pauze'] ; ?>
this is my script, i found on this link
<?php
session_start();
?>
<form action="msa_pauze.php" method="POST">
<td> <input type="submit" name="start" value="Start"></td>
<br><br>
<td> <input type="submit" name="end" value="End"></td>
</form>
<?php
if(isset($_POST['start'])) {
date_default_timezone_set('Europe/Zagreb');
$time_start = date('Y-m-d H:i:s');
$_SESSION['start'] = $time_start;
echo "time start now $time_start <br>";
}
if(isset($_POST['end'])) {
date_default_timezone_set('Europe/Zagreb');
$time_end = date('Y-m-d H:i:s');
$_SESSION['end'] = $time_end;
echo "time was ended $time_end <br>";
$sst= new DateTime($_SESSION['start']);
$eet= new DateTime($_SESSION['end']);
$diff = date_diff($eet, $sst);
$timeelapsed = $diff->format('%r %a days, %h hours, %i minutes and %S seconds');
echo $timeelapsed;
}
?>

Related

Trouble with dates in php

I want to print the date every three months before one year past,from the date selected by user, but when i made the increment the loop breaks and only prints the fist date, could help me, please
this is my code in PHP
$fecha = date('m/d/Y',strtotime($_POST['fecha']));
printf( date('d/m/Y',strtotime($fecha)).'----');
$fin = date('m/d/Y',strtotime($fecha."+ 1 year"));
printf(date('d/m/Y',strtotime($fin)).'----');
if($fecha<$fin){
$fecha = date('m/d/Y',strtotime($fecha."+ 1 month"));
printf( date('d/m/Y',strtotime($fecha)));
}
<form method="POST" action="./fechas.php">
<input type="date" name="fecha" id="fecha">
<input type="submit" value="enviar">
</form>
This is the output:
And i want to print this:
15/10/2020----
15/11/2020----
15/12/2020---
...
You're repeatedly reformatting and reparsing dates and intervals with the most unreliable functions when there's an entire DateTime library to make your life easier.
$input = new DateTime('2020-09-24', new DatetimeZone('UTC'));
$past = (clone $input)->sub(new DateInterval('P1Y'));
$period = new DateInterval('P3M');
$cur = clone $past;
do {
echo $cur->format('Y-m-d') . "\n";
$cur->add($period);
} while( $cur <= $input );
Output:
2019-09-24
2019-12-24
2020-03-24
2020-06-24
2020-09-24

How to subtract a DateTime by a changing time

I've seen various posts asking how to subtract a specific number of hours, days, etc from a DateTime - but my question is a bit different.
Say I have a user log in, and the system records the date/time. Every second, a timer increases based on the difference between the current date/time and the recorded date/time - effectively creating a log-in timer. Then, the user decides to pause the timer, so the system records pause start and pause end (for when they resume). What I would like to do is make the displayed time subtracted by the pause time - such that the timer doesn't 'increase' while paused. Because I'm not using an actual counter adding up every second, in which case I could just not count up during lunch, I am unaware how to calculate the proper value on the timer.
Here is the code on displaying the timer (part of incriment.php):
date_default_timezone_set('America/Chicago');
$date = new DateTime(date('m/d/Y H:i'));
$date2 = new DateTime(date($_SESSION['date_in'] . ' ' .
$_SESSION['time_in']));
$interval = $date->diff($date2);
$interval = $interval->format('%H:%I');
$_SESSION['current_timer'] = $interval;
echo $_SESSION['current_timer'];
And here is the code on being paused
if(isset($_SESSION['paused']) && $_SESSION['paused'] === true) {
echo '<div class="info">';
echo '<img src="images/information-button" style="max-width:3em">';
if(isset($_SESSION['pause_start'])) {
date_default_timezone_set('America/Chicago');
if(isset($_SESSION['pause_end'])) {
$time = $_SESSION['pause_end']->diff($_SESSION['pause_start']);
echo '<br>Current pause time: ' . $time->format('%H:%I');
} else {
$time = new DateTime(date('H:i'));
$time = $time->diff(new DateTime($_SESSION['date_pause_start'] . ' ' . $_SESSION['pause_start']));
$_SESSION['pause_timer'] = $time->format('%h hours, %i minutes');
echo '<br>Pause timer: ' . $time->format('%h hours, %i minutes');
}
echo '</div>';
}
}
TLDR; How can I subtract a DateTime by an object returned by diff when I don't know if that diff will return minutes (say 30 minutes) or hours (say 1 hour, 30 minutes). I can't do this as a result of not knowing that, nor can I do something like $date->modify("+30 minutes") because I don't know if it's minutes or hours or what. I feel like it should be easy because in my lunch calculations, $time is displaying the time paused (ex: 30 minutes) and by using that into a string I could use the$date->modify strategy - but that's not working (See below what I tried in my incriment.php I showed earlier)
$interval = $interval->format('H:i');
if(isset($_SESSION['pause_timer'])) {
$interval = new DateTime(date($interval));
$interval = $interval->modify("-". $_SESSION['pause_timer']);
echo '-' . $_SESSION['pause_timer'];
}
But that echo's out -0 hours, 40 minutes if the user was paused for 40 minutes - and changes the time from 01:48 to 14:18 which is really confusing as it should be 1:08 obviously. That means to me that I'm improperly using the DateTime for my situation, is there a better solution
Thank you!
Edit: The user can only pause once per session for simplicities sake
I appreciate the replies in comments [even those they deleted ;) ], I managed to get it working by changing the paused code at the $_SESSION['pause_timer'] = $time->format('%h hours, %i minutes') into $_SESSION['pause_timer'] = $time->format('-%h hours, -%i minutes'). My problem was that I was subtracting only the hours, so when my time was only in minutes it added the minutes and subtracted the 0 hours!

Calculate time difference button

Hi I am new to javascript and php. I have a form that has three text boxes, starttime, endtime and results. I am trying to take the starttime and endtime and find how much time has passed and display this in the results. How can I go about this?
here is my html:
<form action="JobChangeTimeSheet.php" method="GET">
Machine Stopped at:
<input type="time" name="start_date"/>
End of TO:
<input type="time" name="since_start"/>
<input type="submit">
Total time
<?PHP
if (! empty($_GET['start_date'])){
$start_date = new DateTime($_GET['start_date']);
$since_start = $start_date->diff(new DateTime($_GET['since_start']));
echo $since_start->days.' days ';
echo $since_start->h.' hours';
echo $since_start->i.' minutes';
}
?>
</form>
You can see there are 2 text boxes, a button, and a third disabled text box. I am trying to view the difference in minutes between the two text boxes in the third text box
Since you do not have a code I can work on, I will guide you exactly through the steps on how to do this.
Load your HTML input in PHP vars named $start_date and $end_date. Use these lines:
$start_date = new date("Y-m-d H:i:s",strtotime($start_date));
$end_date = new date("Y-m-d H:i:s",strtotime($end_date));
$interval = $start_date->diff($end_date);
$hours = $interval->format('%h');
$minutes = $interval->format('%i');
echo 'Difference in minutes is: '.($hours * 60 + $minutes);
PS: You are talking about Javascript in your question but no Javascript code has been presented in your code. Are you using some sort of DateTimePicker?

Comparing time in PHP

I am comparing a deadline time from my database which is on a 24-hour format (like 3:00 = 15:00) to the time now.
For example, if a student wasn't able to submit on the due time, an upload link will be greyed out.
I'm okay with the date comparison, my problem is the time.
Here's my current code:
$date = date("Y-m-d");
$time = strtotime(date('G:i:s'));
$deadtime = strtotime($r['upload_deadtime']);
/*------$deadtime = 15:00:00 ---------*/
if(date($r['upload_deadline']) >= $date && $deadtime > $time){
echo '<td>upload</td>';
}
else{
echo '<td><a title="your too late! haha!" style="color:grey">upload</a></td>';
}
Update: let's just forget about the date comparison, what I'm trying to say is how can I compare my deadline time (which is on a 24-hour format (like 3:00:00 = 15:00:00)) to the time now.
Here's my current code:
$time = strtotime(date('G:i:s')); /*which returns 23:15:42 instead of 14:15:42 */
$deadtime = strtotime('15:00:00');
if($deadtime > $time){
echo '<td>upload</td>';
}
else{
echo '<td><a title="your too late! haha!" style="color:grey">upload</a></td>';
}
date_default_timezone_set('Asia/Manila');
$deadtime = strtotime("15:00:00");
if ($deadtime - time() > 0){
echo '<td>upload</td>';
}else{
echo '<td><a title="your too late! haha!" style="color:grey">upload</a></td>';
}
This may solve your time comparison issue!!
strtotime("15:00:00") will convert time into unix timestamp of today's 15:00:00 and time() have current unix timestamp.
You just have the comparison backwards on your time check.
You are checking if the deadline date is in the future (assuming the script always runs in the present) and then you are checking that the deadline time is less than the current time (IE before), on a date time epoch value.
With the check you are doing on the strtotime, you do not need to check the dates, as they are already included with the date and time by means of epoch.
Simply do:
if($deadtime > $time){
echo '<td>upload</td>';
} else {
echo '<td><a title="your too late! haha!" style="color:grey">upload</a></td>';
}
This will only show the upload link in the table if the deadline time is in the future.
EDIT:
In the case of your new code, you just need to make the deadtime a strtotime of the deadline date and time stamp from your dBase. Then the code will work.
You are still also comparing the wrong way around!
Example:
/* deadtime = strtotime of datetimestamp in format yyyy-mm-dd G:i:s */
/* $time = strtotime of now. */
if($deadtime > $time){
echo '<td>upload</td>';
} else {
echo '<td><a title="your too late! haha!" style="color:grey">upload</a></td>';
}
Use time PHP's DateTime::Diff
// Current Date and Time
$date_time_now = new DateTime();
// Date Time values from DB (Assuming it's coming from database)
$date_time_deadline = new DateTime('2014-09-08 15:00:00');
// Calculate difference
$difference = $date_time_now->diff($date_time_deadline);
// Output difference in human-readable format
echo "Difference: " . $difference->format('%d days, %h hours, %i minutes, %s seconds');
http://php.net/manual/en/datetime.diff.php
Here's my working code. I think you'll know that my point is.
date_default_timezone_set('Asia/Manila');
$time = date('H:i:s');
$deadline_time = date("h:i a",strtotime($r['upload_deadtime']));
list($hours,$mins,$secs) = explode(":",$time);
$hours = date("H") + 9;/*-gives me wrong hours so i got to modify it-*/
$time_array = array($hours,$mins,$secs);
$new_time =implode(":",$time_array);
$deadtime = strtotime($deadline_time);
$time_now = strtotime($new_time);
if($r['upload_deadline'] < $date && $deadtime < $time_now){/*-compares the date and time-*/
echo '<td>upload</td>';
}
else{
echo '<td><a title="your too late! haha!" style="color:grey">upload</a></td>';
}

Validating Time & Date To Be At Least A Certain Amount Of Time In The Future

I've built a reservation form for a taxi company which works fine, but I'm having an issue with users making reservations that are due too soon in the future.
Since the entire form is kind of long, I first want to make sure the user is not trying to make a reservation for less than an hour ahead of time, without them having to fill out the whole form.
This is what I have come up with so far, but it's just not working:
<?php
//Set local time zone.
date_default_timezone_set('America/New_York');
//Get current date and time.
$current_time = date('Y-m-d H:i:s');
//Set reservation time variable
$res_datetime = $_POST['res_datetime'];
//Set event time.
$event_time = strtotime($res_datetime);
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Check Date and Time</title>
</head>
<?php
//Check to be sure reservation time is at least one hour in the future.
if (($current_time - $event_time) <= (3600))
{
echo "You must make a reservation at least one hour ahead of time.";
}
?>
<form name="datetime" action="" method="post">
<input name="res_datetime" type="datetime-local" id="res_datetime">
<input type="submit">
</form>
<body>
</body>
</html>
How can I create a validation check to make sure the date and time of the reservation is at least one hour ahead of time?
If you do this (add the echo line) you will see a big problem, you are mixing 2 different date types!
echo "current: $current_time Event: $event_time";
if (($current_time - $event_time) <= (3600))
Okay, I figured it out. Here's what I came up with:
<?php
//Set time zone:
date_default_timezone_set('America/New_York');
//Set current time:
$current_time = date("Y-m-d H:i:s");
//Convert current time to timestamp:
$current_timestamp = strtotime($current_time);
//Set the minimum amount of time in advance a reservation can be made:
$min_time = strtotime("+1 hour", strtotime($current_time));
//Set event date:
$event_date = $_POST['event_date'];
//Set event time:
$event_time = $_POST['event_time'];
//Convert event time to timestamp:
$event_timestamp = strtotime("$event_date . $event_time");
//Set availability:
//If required fields are set and validated:
if (isset($event_date, $event_time)) {
//If reservation time is made in the past:
if ($event_timestamp < $min_time && $event_timestamp < $current_timestamp) {
$availability = "in_the_past";
//If reservation time is less than the required amount of time in advance:
} elseif ($event_timestamp > $current_time && $event_timestamp < $min_time) {
$availability = "too_soon";
//If a reservation is made for when no one may be checking email in time:
} elseif ($event_timestamp > strtotime('today 8:00pm') && $event_timestamp < strtotime('tomorrow 6:00am')) {
$availability = "unavailable";
} else {
$availability = "available";
}
Thanks again for everyone's help.

Categories