Countdown to certain date and adding x hours - php

Timer Main
$curDate = date("Y-m-d H:i:s", strtotime("-8 hours"));
$timecountdownend = strtotime($curDate) + strtotime("+1 hours");
$timecountdownstart = strtotime("-8 hour");
$timeleft = $timecountdownend - $timecountdownstart;
if (isset($_POST['type']) && $_POST['type'] == "timerupdate") {
echo $timeleft;
}
?>
Timer Update 5 Seconds
$(document).ready(function(){
var timerText = $("[timer]");
setInterval(function(){
$.post("timer.php", {type: "timerupdate"}, function(data){
timerText.html("Time Left:" + data + " seconds timer.")
});
}, 5000);
});
WHAT ARE YOU TRYING TO ACHIEVE?
The idea is when a user reserves an item, expiration date is set into the database so that the USER that reserved the item cannot hold it forever. So for example:
User A: Reserve Item A.
[SERVER] $database->insert("reservation", $curDate);
[SERVER] 2016-04-03 16:00:00 (After 30 minutes this item is expired)
That what's supposed to happen in the back-end.
WHAT HAVE YOU TRIED?
I've done tons of googling to see how I could add x hours or minutes to the current date and pass that on to become a unix timestamp.
WHAT IS YOUR PROBLEM?
Whenever I try the code above it works but doesn't come up with the right output I need. Specifically the problem is at $timecountdownend = strtotime($curDate) + strtotime("+1 hours");
** NEW **
date_default_timezone_get("America/New York");
$curDate = date("Y-m-d H:i:s", strtotime("-8 hours"));
$date = new DateTime($curDate);
date_add($date, date_interval_create_from_date_string('2 hour'));
$timecountdownend = strtotime($date->format('Y-m-d H:i:s'));
$timecountdownstart = strtotime("-8 hour");
$timeleft = $timecountdownend - $timecountdownstart;
if (isset($_POST['type']) && $_POST['type'] == "timerupdate") {
echo $timeleft;
}
OUTPUT: 7200 seconds (STUCK though). It's precise but it's not counting down.

Did you consider http://php.net/manual/en/datetime.add.php ?
the only tricky part is to understand how this syntax work : $date->add(new DateInterval('P7Y5M4DT4H3M2S')); P7 means add 7 years H3 means add 3 hours
Once you save or update the date in your database, send a copy along with the response and in your final response document put this :
https://jsfiddle.net/o740okn4/5/
You will need to make these calls from CDN or get the scripts from git
moment.min.js
moment-duration-format.min.js
https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.12.0/moment.min.js
and
https://cdnjs.cloudflare.com/ajax/libs/moment-duration-format/1.3.0/moment-duration-format.min.js

Related

php - how to echo out the next time entry I have in an array?

I'm working on a tick based space game http://ricarion.com/ but the ticks only run between certain hours.
08:00-16:30 - run every 30 minutes via a cron job. In the nav bar at the top I want to add "Next Tick: 08:30 06/02/20" for example.
So I was thinking of creating an array:
$tick_times[] = array();
$tick_times[] = 08:00;
$tick_times[] = 08:30;
$tick_times[] = 09:00;
...
$tick_times[] = 16:30;
And then this is where I get stuck, how do I check the existing time, and then compare that against the array selecting the next future time? i.e. It's now 08:34, so the return should be 09:00?
Did you need an array or just want to calculate the next 30-minute interval?
If so this may be similar to:
Round minute down to nearest quarter hour
You do modulo division of 1800 seconds on the current time and add the answer (time remainder of time to the next interval) to the then-current time to get the next event.
<?php
$current_date = date('d-M-Y g:i:s A');
echo $current_date."\n";
$current_time = strtotime($current_date);
$frac = 1800;
$r = $current_time % $frac;
$new_time = $current_time + ($frac-$r);
$new_date = date('d-M-Y g:i:s A', $new_time);
echo $new_date."\n";
http://codepad.org/xs9lMCRQ
Get the now time format it and compare it. In your case you maybe format your $tick_time to the same format like current time.
$date = new DateTime('now');
$date = $date->format('Y-m-d H:i:s');
foreach ($tick_times as $tick_time) {
$date_added = new DateTime($tick_time);
if (strtotime($date_added) == strtotime($date)) {
//do your stuff here
}
}

Converting hours to timestamps

To convert a date to timestamp, I usually do this- strtotime ("2018-05-17 05:04:34) but now, I want to convert just hours (without date) e.g. 02:00:00 to timestamp. How do I do this?
Why I need this is to compare if a certain time is greater than the hour specified. This is what I am doing:
$reported = strtotime("2018-05-17 05:04:34");
$respons = strtotime("2018-05-17 17:04:34);
$response_time = $respons - $reported;
I want to be to check if $response_time is greater than 1 hour.
There is DateTime::diff, which probably does what you need
https://secure.php.net/manual/de/datetime.diff.php
In your case that should be
$datetime1 = new DateTime("2018-05-17 05:04:34");
$datetime2 = new DateTime("2018-05-17 17:04:34);
$interval = $datetime1->diff($datetime2);
echo $interval->format('H hours');
Strtotime has no problem parsing a time without a date.
No need to fake a date which will come back and bite you with daylight savings.
I also added a check to see if the start/end is "reversed".
$start= "2018-05-17 05:04:34";
$end = "2018-05-17 17:04:34";
//Note that it's intentionally reversed
$diff = strtotime(substr($start,11))-strtotime(substr($end,11));
//If the calculation was reversed add one day in seconds
if($diff <0) $diff += 86400;
If($diff >3600){
Echo "more than one hour";
}Else{
Echo "less than one hour";
}
https://3v4l.org/g1jZH
I believe only I have understood your question correctly.
I want to convert just hours (without date) e.g. 02:00:00 to timestamp.
There's no Date component here.
Okay, I assume they are of same date. If that's the case, just append an arbitrary date in front of the two to make the strtotime() function work:
$start = "05:04:34";
$end = "17:04:34";
$reported = strtotime("2018-05-17 " . $start);
$respons = strtotime("2018-05-17 " . $end);
$response_time = $respons - $reported;
if ($response_time > 3600)
echo "More than hour!";
else
echo "Less than hour!";
Note: This doesn't work if the start time is 17:00 and end time is say, 08:00 - which occurs in the next day. You have to make sure if the start time is greater than end time, then you have to add one more day to the end time.
I like the DateTime class, give this a try:
<?php
$reported = new DateTime('2018-05-17 05:04:34');
$reported->modify('+2 hours');
$now = new DateTime();
echo $now < $reported ? 'less than 2 hours' : 'more than 2 hours';
See it here https://3v4l.org/T7BEL
See the DateTime class docs here http://php.net/manual/en/class.datetime.php

PHP - How to check if current day/time is between two weekdays including time (from - to)

I need to check if current date and time is between two weekdays which include time (from and to). There can be multiple records in the db and week days are stored via PHP date('N') where 1 (for Monday) through 7 (for Sunday) as well as hour - minute is stored via time.
For instance, a stored rule can be the following:
week_day_from : 5 (Friday)
week_hour_from : 16:00:00
week_day_to : 7 (Sunday)
week_hour_to : 18:00:00
or even
week_day_from : 7 (Sunday)
week_hour_from : 10:00:00
week_day_to : 2 (Tuesday)
week_hour_to : 12:00:00
How can I determine if current day/time applies in one of the rules? The main idea is to hide some results if one of the rule applies (i.e. do not show this meal after friday 16:00 and before Sunday 18:00)
thank you in advance
The function getdate will give you more exact information. The function getDate() will return an array containing information about the weekday and time. By having the interval,you can determine if applies.
found something....
had to create pseudo dates in order to use strtotime and compare with current date time. Pseudo dates are created via conditions as shown below which are commented to describe my logic.
I would much better prefer a MySQL query based solution rather than fetching all rules and compare but I can not find a way. I would be gratefull if you check my code and tell me what you think. Flaw may be possible...
$daynow = date("N"); //$daynow = 7;
$datetimenow = date("d-m-Y G:i:s");
if($row['week_day_from'] > $row['week_day_to'])
{// case from saturday(6) to thursday(4)
if($daynow == 7)
{
$check_from = date("d-m-Y", strtotime("Sunday + ".$row['week_day_from']." Days - 1 week"));
$check_to = date("d-m-Y", strtotime("Sunday + ".$row['week_day_to']." Days"));
}
else
{
$check_from = date("d-m-Y", strtotime("Sunday + ".$row['week_day_from']." Days - 2 week"));
$check_to = date("d-m-Y", strtotime("Sunday + ".$row['week_day_to']." Days - 1 week"));
}
}
else
{// case from thursday(4) to saturday(6)
if($daynow == 7)
{
$check_from = date("d-m-Y", strtotime("Sunday + ".$row['week_day_from']." Days"));
$check_to = date("d-m-Y", strtotime("Sunday + ".$row['week_day_to']." Days"));
}
else
{
$check_from = date("d-m-Y", strtotime("Sunday + ".$row['week_day_from']." Days - 1 week"));
$check_to = date("d-m-Y", strtotime("Sunday + ".$row['week_day_to']." Days - 1 week"));
}
}
if
(
strtotime($datetimenow) >= strtotime($check_from." ".$row['week_hour_from'])
AND
strtotime($datetimenow) <= strtotime($check_to." ".$row['week_hour_to'])
)
{
//RULE APPLIES
}

PHP Event booking: get time in increments of 30 minutes is 1 hour out

I am trying to get a select box with a list of time increments from 00:00 to 24:00.
The time increments are an associative array of seconds to the display time like this:
1800 => 00:30
Then when someone selects a date, I plan to convert the date (e.g. 2016/9/16) into seconds and then add the time that they selected on to those seconds to get the date time of their event.
To do this I am generating the time increments like this.
public function getIntervals($start_time = '00:00', $end_time = '24:00', $increments = '30')
{
$today = strtotime(date('Y/m/d', time())); // seconds for 2016/9/16
$seconds_start = strtotime(date('Y/m/d', time()) . ' ' . $start_time) - $today;
$seconds_end = strtotime(date('Y/m/d', time()) . ' ' . $end_time) - $today;
while ($seconds_start < $seconds_end) {
$intervals[$seconds_start] = date("H:i", $seconds_start);
$seconds_start = strtotime('+' . $increments . ' minutes', $seconds_start);
}
return $intervals;
}
However my time intervals are one hour out.
If someone selected '2016/9/17 at 01:00 in the morning' the value in seconds of 01:00 in the morning is '0'.
If I add '0' to strtoseconds('2016/9/17') I am going to get '2016/9/17 at 00:00'.
So here I am,one hour out. I assume this is due to my server time being set to paris +1hr, but I have no idea how to fix it.
$timediff = 3600;
$paris_00_time = strtotime(date('Y-m-d '.'00:00'));
$paris_selected_time = $paris_00_time+1800;
$my_time = date('Y-m-d H:i:s',$paris_selected_time-$timediff);
print_r($my_time);
you can declare $timediff=3600; ( 1 hour )
$paris_00_time = strtotime(date('Y-m-d '.'00:00'));
after someone choose the date ( ex: [1800] => 00:30 ) and is submitted you can process the date
$paris_selected_time = $paris_00_time+1800;
$my_time = date('Y-m-d H:i:s',$paris_selected_time-$timediff);
output: 2016-09-15 23:30:00
I don't really remember where, but you can change your timezone. Search by PHP timezone and you will find from the official website a list with all the possible country/city. You just need to set a variable with the country/city you need and that's it. I don't know if you can do it in your PHP script or need to change your config files in the server.

Time difference not working when year changes

I have a script that was working, well is working but not properly. The function is suppose to work out the time difference between two dates/times.
The First date is the Current Date and Time (Date + Hr:Min) and the second date is chosen by a user.
The purpose is to show error when the current date/time is within 24 hours from the user chosen date. i.e. if today is 23/20/2012 16:00 and the user chooses 24/10/2012 15:00 (this mean its within 24 hours) but if user chooses 26/10/2012 19:00 then its passed 24 hours.
Now this works fine but when the date changes its year (when user selected any date after 31st Dec 2012.. it assumes its still within 24 hours.. and im quite baffled how this happens.. can anyone shed some light what I've done wrong?
$dt = $_GET['dt']; $tm = $_GET['tm'];
// Current Date an time (Hrs & Mins)
$date1 = date("Y-m-d H:i");
// Chosen Date/Time
$date2 = date("Y-m-d", strtotime( "$dt" ) );
$diff = strtotime($date2." $tm") + - strtotime($date1);
if($diff/3600 < 24)
echo "0";
else
echo "1";
The following is the corresponding Ajax that makes th call
function getAjaxTime()
{
xmlHttp=GetXmlHttpObject();
if (xmlHttp==null)
{
alert ("Your browser does not support AJAX!");
return;
}
dt = document.frm.arrival_date.value;
tm = document.frm.arrival_hour.value +':'+document.frm.arrival_min.value;
xmlHttp.open("GET","<?php echo $base_dir;?>/admin/get/timediff.php?dt="+encodeURI(dt)+"&tm="+encodeURI(tm),false);
xmlHttp.send(null);
return xmlHttp.responseText;
}
I would try something like this:
function isDateWithin24Hours($targetDate, $currentDate = 'now') {
$targetDate = new DateTime($targetDate);
$currentDate = new DateTime($currentDate);
$interval = $targetDate->diff($currentDate);
//%a = total number of days
if ($interval->format('%a') > 1) {
return (int) false;
}
return (int) true;
}
echo isDateWithin24Hours('2012-10-24 19:00:00');
echo isDateWithin24Hours('2012-10-24 19:00:00', '2012-10-23 18:00:00');
According to the php manual - http://us3.php.net/manual/en/datetime.formats.date.php - your date is not a valid format:
24/10/2013 // with / as deliminators
These would be valid
24-10-2013 // with - as deliminators
10/24/2013 // with / as deliminators and as m/d/Y
Update-
Also, the following format is invalid in strtotime & date-
Thursday, 10 May, 2012 00:30
But this would be valid -
Thursday, May 10, 2012 00:30
Update #2
In fact once your $_GET['dt'] is in a valid php format, you could simplify your code to-
$dt = $_GET['dt']; $tm = $_GET['tm'];
// Current Date an time (Hrs & Mins)
$date1 = date("Y-m-d H:i");
$diff = strtotime($dt." ".$tm) + - strtotime($date1);
if($diff/3600 < 24)
echo "0";
else
echo "1";

Categories