populate time interval with 30 mintutes between 2 dates - php

I have 2 time strings for example OPEN = 11:00 and closed is 02:45
now the 02:00 is the next day so i to the following:
//open = string 11:00
//closed= string 02:45
$open = \DateTime::createFromFormat('H:i', $open);
$closed = \DateTime::createFromFormat('H:i', $closed);
if ($open > $closed) $closed->modify('+1 day');
now i have 2 proper datetime formats. Now i want to set a time interval of 30 minutes from the open time to the close time. How can i do this? i have read i can add like this
->add(new DateInterval('PT30M') b
ut it will add till the end of the day.. but in this case its open till the next day, so i want it to populate till 2:45AM
how can i do this?

You where on the right track. Here is how to do it using DateInterval('PT30M').
$strOpen = '11:00';
$strClose = '02:45';
$open = DateTime::createFromFormat('H:i', $strOpen);
$closed = DateTime::createFromFormat('H:i', $strClose);
if ($open > $closed) $closed->modify('+1 day');
// I display not only the time, but the day as well to show that it is
// incrementing to the next day.
echo 'open: ' . $open->format('D H:i') . "<br />\n";
while ($open < $closed) {
$open->add(new DateInterval('PT30M'));
// because incrementing on the half hour and our finish is on the 15 min,
// the last is $open < $close in the while statement will be true but
// this loop will generate a time after $closed so we do another check
// now to eliminate that issue
if ($open < $closed) {
echo '+30min: ' . $open->format('D H:i') . "<br />\n";
}
}
echo 'closed: ' . $closed->format('D H:i') . "<br />\n";

Related

I want to set the winning day of the event as a weekday, but is it possible to resolve the error?

// holiday array
$holy = [
'2020-12-23',
'2020-12-24',
'2020-12-25',
'2020-12-28',
'2020-12-29',
];
$inputDate = '2020-12-23'; // input
$outputDate = get_date($inputDate);
echo "Winning Day: " . $outputDate . "<br />";
echo "<br />";
function get_date($chkDate)
{
global $holy;
$chkDateYoil = date("w", strtotime($chkDate)); // sat(6), sun(0)
if ($chkDateYoil == 6) {
// Saturday when + 2
$timestamp = strtotime($chkDate . " +2 days");
$chkDate = date("Y-m-d", $timestamp);
} else if ($chkDateYoil == 0) {
// Sunday when + 1
$timestamp = strtotime($chkDate . " +1 days");
$chkDate = date("Y-m-d", $timestamp);
}
// If it's a weekday, compare it array
foreach ($holy as $key => $holyday) {
if ($chkDate == $holyday) {
// holiday when + 1
$day_plus = 8 - $chkDateYoil;
$timestamp = strtotime($chkDate." +".$day_plus." days");
$chkDate = date("Y-m-d", $timestamp);
}
}
return $chkDate;
}
Hello, let me ask a question.
The following codes are:
Is the input value weekend?
Or are they included in the array?
in accordance with the judgment
Weekday extraction code.
But there is an error.
in my estimation
December 30th is supposed to come out.
By the way, January 2, 2021 is the result.
Why is that?
sorry
i don't write english very well
Thank you for reading.
The problem is in this line: $day_plus = 8 - $chkDateYoil;, which is calculating the date of the next Monday the first time it's executed.
You're then looping through the rest of the $holy array, and updating $chkDate if necessary, but you're not recalculating the value of $chkDateYoil, so the output depends on the day of the week you run this. Today (23rd December) it stops on 2nd January
Your code can be simplified by just incrementing the date by 1 day and performing the checks again, continuing until you get a result. I've also used the PHP function in_array() to simplify the search of the $holy array, and incorporated it into the same test as Saturday and Sunday.
// holiday array
$holy = [
'2020-12-23',
'2020-12-24',
'2020-12-25',
'2020-12-28',
'2020-12-29',
];
$inputDate = '2020-12-23'; // input
$outputDate = get_date($inputDate);
echo "Winning Day: " . $outputDate . "<br />";
echo "<br />";
function get_date($chkDate)
{
global $holy;
do {
$chkDateYoil = date("w", strtotime($chkDate)); // sat(6), sun(0)
if (($chkDateYoil == 0) || ($chkDateYoil == 6) || (in_array($chkDate, $holy))) {
$timestamp = strtotime($chkDate . " +1 days");
$chkDate = date("Y-m-d", $timestamp);
} else {
return $chkDate;
}
} while (true);
}

PHP if date is older than X days

I have some problems with dates. I need make if like --->
if your activity is less than 1 day do somethink
else if your activity is more than 1 day and less than 3 do moething else
else if your activity is more than 3 do moething else
I need this in PHP. My actual code is:
if (strtotime(strtotime($last_log)) < strtotime('-1 day') ) {
$prom .= "" . json_encode('last_activity') . ": " . json_encode("inactive less than 1 day") . ",";
} else if (strtotime($last_log) > strtotime('-1 day') && strtotime($last_log) < strtotime('-3 day')) {
$prom .= "" . json_encode('last_activity') . ": " . json_encode("inactive more than 1 day and less than 3 days") . ",";
} else if (strtotime($last_log) > strtotime('-3 day')) {
$prom .= "" . json_encode('last_activity') . ": " . json_encode("inactive more than 3") . ",";
}
I think I really don't understand date calculations.
Date_diff is much easier in this case:
$datetime1 = date_create(); // now
$datetime2 = date_create($last_log);
$interval = date_diff($datetime1, $datetime2);
$days = $interval->format('%d'); // the time between your last login and now in days
see: http://php.net/manual/en/function.date-diff.php
Or in your way:
if(strtotime($last_log) < strtotime('-1 day')){
// it's been longer than one day
}
If you want to do it with strtotime, do it like this:
date_default_timezone_set('SOMETHING FOR YOU');
$last_log = '-0.5 day';
$last_log_time = strtotime($last_log);
$minus1day_time = strtotime('-1 day');
$minus3day_time = strtotime('-3 day');
echo $last_log_time . "<br>";
echo $minus1day_time . "<br>";
echo $minus3day_time . "<br>";
if ($last_log_time < $minus3day_time)
{
echo "inactive more than 3";
}
elseif ( ($last_log_time <= $minus1day_time) && ($last_log_time >= $minus3day_time) )
{
echo "inactive more than 1 day and less than 3 days";
}
elseif ($last_log_time > $minus1day_time)
{
echo "inactive less than 1";
}
Couple things I changed from your code:
remove the strtotime(strtotime()). Do not do it twice!
For your second if, I added parentheses to ensure correct evaluation of conditions.
I reversed the order of your if. First check if it is very old (so < -3). Then check if it is between -3 and -1. Then check between -1 and now.
Added <= and >=. The = cases were missing from your code. So if the last_log was == -1, it was not processed ever.
I replace "else if" by "elseif".
I used variables because recalculating strtotime all over is wasteful. And it makes the code less readable IMHO.
Then apply the json_encode comment.
To explain why the logic was reversed:
the last login of a user will always be before now.
lets say that the user's last_login is 5 days ago. strtotime($last_login) will be smaller than strtotime('-1 days'), so the if will be true. But that is not what the OP wants! He wants here the case where the last login is older than 3 days.
Remember that we are comparing numbers in the past, so the smaller, the older.
$dateLog = new DateTime($last_log); // format if needed
$tomorrow = new DateTime("tomorrow");
$yesterday = new DateTime("yesterday");
$threeDaysAgo = new DateTime("-3 days");
if ($dateLog < $yesterday) {
// Do what you want
} else if ($dateLog > $yesterday && $dateLog < $threeDaysAgo) {
// Do another thing
} else if ($dateLog > $threeDaysAgo) {
// ...
}
The doc is here : http://php.net/manual/en/datetime.diff.php

Count overall time between two timestamps per user

Currently I'm stuck with some MySQL queries.
I have a table like this:
ID|USERID|USERNAME|STARTTIME|ENDTIME|COMMITTYPE
The users click buttons in a frontend -> Start <- and -> Stop <-.
This creates a db entry with their respective duties, starttime and endtime. So, each click on start creates a new row/entry in the db and will get finished by the click on the stop button.
My problem, is there a chance to count the overall time between the start time and the end time per user and commit type?
This probably work
SELECT USERID, COMMITTYPE, MIN(STARTTIME), MAX(ENDTIME),
SUM(TIME_TO_SEC(TIME_DIFF(ENDTIME - STARTTIME))/3600) hours FROM tablename
GROUP BY USERID, COMMITTYPE
Do you refer to something like this?
SELECT COMMITTYPE, USER, (ENDTIME - STARTTIME) AS ELLAPSED_TIME
FROM YOUR_TABLE GROUP BY COMMITTYPE, USERID;
SELECT DATEDIFF('new_date', 'old_date');
// eg
SELECT DATEDIFF('2006-04-01','2006-04-01');
IG GETTING USE LINUX
<?php
// Set timezone
date_default_timezone_set("UTC");
// Time format is UNIX timestamp or
// PHP strtotime compatible strings
function dateDiff($time1, $time2, $precision = 6) {
// If not numeric then convert texts to unix timestamps
if (!is_int($time1)) {
$time1 = strtotime($time1);
}
if (!is_int($time2)) {
$time2 = strtotime($time2);
}
// If time1 is bigger than time2
// Then swap time1 and time2
if ($time1 > $time2) {
$ttime = $time1;
$time1 = $time2;
$time2 = $ttime;
}
// Set up intervals and diffs arrays
$intervals = array('year','month','day','hour','minute','second');
$diffs = array();
// Loop thru all intervals
foreach ($intervals as $interval) {
// Create temp time from time1 and interval
$ttime = strtotime('+1 ' . $interval, $time1);
// Set initial values
$add = 1;
$looped = 0;
// Loop until temp time is smaller than time2
while ($time2 >= $ttime) {
// Create new temp time from time1 and interval
$add++;
$ttime = strtotime("+" . $add . " " . $interval, $time1);
$looped++;
}
$time1 = strtotime("+" . $looped . " " . $interval, $time1);
$diffs[$interval] = $looped;
}
$count = 0;
$times = array();
// Loop thru all diffs
foreach ($diffs as $interval => $value) {
// Break if we have needed precission
if ($count >= $precision) {
break;
}
// Add value and interval
// if value is bigger than 0
if ($value > 0) {
// Add s if value is not 1
if ($value != 1) {
$interval .= "s";
}
// Add value and interval to times array
$times[] = $value . " " . $interval;
$count++;
}
}
// Return string with times
return implode(", ", $times);
}
?>
///
echo dateDiff("2010-01-26", "2004-01-26") . "\n";
echo dateDiff("2006-04-12 12:30:00", "1987-04-12 12:30:01") . "\n";
echo dateDiff("now", "now +2 months") . "\n";
echo dateDiff("now", "now -6 year -2 months -10 days") . "\n";
echo dateDiff("2009-01-26", "2004-01-26 15:38:11") . "\n";
OUTPUT
6 years
18 years, 11 months, 30 days, 23 hours, 59 minutes, 59 seconds 2
months 6 years, 2 months, 10 days 4 years, 11 months, 30 days, 8
hours, 21 minutes, 49 seconds

PHP - Populate select options with 15 min time intervals

Hi I am creating a website for a restaurant delivery service. Basically when the customer is checking out, he/she can choose when they want the food to be delivered. I want the select box to contain time intervals of 15 mins ranging from the current time until the close time. The restaurant is open for deliveries between 11:00 to 23:00. The first option I want is to be "As soon as possible", and then the next option is an hour later (rounded to nearest 15mins), and then 15 mins each time. So basically something like this:
(Suppose current time is 13:55)
As soon as possible
15:00
15:15
15:30
15:45
...and so on until close time (23:00)
If the restaurant is closed (after 23:00) then I just want the select box to have an option that says "CLOSED".
Here is what I have tried so far but it is not working:
<select>
<?php
$timenow = date("H:i");
if($timenow >"23:00" || $timenow < "11:00"){
echo '<option value="Closed">CLOSED</option>';
echo "</select>";
}
else{
$deliverytime = date("H:i", strtotime('+15 minutes', $timenow));
echo '<option value="asap">As soon as possible</option>';
while($deliverytime < "23:00" && $deliverytime > "11:00"){
echo '<option value="'. $deliverytime.'">' . $deliverytime . '</option>';
$deliverytime = date("H:i", strtotime('+15 minutes', $deliverytime));
}
echo "</select>";
}
?>
strtotime('+15 minutes', $timenow) is not correct. The second argument should be a timestamp, not a string. You want something like strtotime('+15 minutes', time()) or just leave off the second argument (current time is the default).
A better approach is to always work with the timestamps until you output. That makes rounding and comparisons much easier.
<select>
<?php
$timenow = time();
$opentime = strtotime('11:00');
$closetime = strtotime('23:00');
if($timenow > $closetime || $timenow <= $opentime){
echo '<option value="Closed">CLOSED</option>';
echo "</select>";
}
else{
// you said you wanted the time to start in 1 hour, but had +15 minutes...
$deliverytime = strtotime('+1 hour', $timenow);
// round to next 15 minutes (15 * 60 seconds)
$deliverytime = ceil($deliverytime / (15*60)) * (15*60);
echo '<option value="asap">As soon as possible</option>';
while($deliverytime <= $closetime && $deliverytime >= $opentime) {
echo '<option value="'. date('H:i', $deliverytime) .'">' . date('H:i', $deliverytime) . '</option>'."\n";
$deliverytime = strtotime('+15 minutes', $deliverytime);
}
echo "</select>";
}
I can't provide a complete solution but can point you in the right direction.
This code will handle the 15 minute interval parts for you:
$start = new DateTime();
$end = new DateTime('11PM');
$interval = new DateInterval('PT15M');
$period = new DatePeriod($start, $interval, $end);
foreach ($period as $dt)
{
echo $dt->format("l Y-m-d") . PHP_EOL;
}
The accepted answer in this Stack Overflow question shows how to get to the nearest 15 minute interval: PHP DateTime round up to nearest 10 minutes
Combine the two and you should have a complete solution to your problem.

Calculating the number of days between two dates

I have a mySQL database.
I need to count the number of days between two dates.
My client is going to fill an input hm_date with January 1, 1979 via php form to create a new record.
I need a field total_days to calculate the total number of days from hm_date to the present day. I need this field to always update itself with each passing day.
How do I make hm_date to appear with total days and be always updated?
I asume this can be achieved server-side?
Should I use strototime() ?
You'll want to use MySQL's DATEDIFF()
DATEDIFF() returns expr1 – expr2 expressed as a value in days from one
date to the other. expr1 and expr2 are date or date-and-time
expressions. Only the date parts of the values are used in the
calculation.
mysql> SELECT DATEDIFF('2007-12-31 23:59:59','2007-12-30');
-> 1
mysql> SELECT DATEDIFF('2010-11-30 23:59:59','2010-12-31');
-> -31
Based on your question I think you would want DATE_DIFF(hm_date, CURRENT_DATE). Just make sure hm_date is in YYYY-MM-DD format.
With PHP:
$daydiff = floor( ( strtotime( $endDate ) - strtotime( $startDate ) ) / 86400 );
$startDate and $endDate can be any valid date format explained here:
http://www.php.net/manual/en/datetime.formats.date.php
Its pretty easy but long.. Please follow following codes
<?php
// Set timezone
date_default_timezone_set("UTC");
// Time format is UNIX timestamp or
// PHP strtotime compatible strings
function dateDiff($time1, $time2, $precision = 6) {
// If not numeric then convert texts to unix timestamps
if (!is_int($time1)) {
$time1 = strtotime($time1);
}
if (!is_int($time2)) {
$time2 = strtotime($time2);
}
// If time1 is bigger than time2
// Then swap time1 and time2
if ($time1 > $time2) {
$ttime = $time1;
$time1 = $time2;
$time2 = $ttime;
}
// Set up intervals and diffs arrays
$intervals = array('year','month','day','hour','minute','second');
$diffs = array();
// Loop thru all intervals
foreach ($intervals as $interval) {
// Set default diff to 0
$diffs[$interval] = 0;
// Create temp time from time1 and interval
$ttime = strtotime("+1 " . $interval, $time1);
// Loop until temp time is smaller than time2
while ($time2 >= $ttime) {
$time1 = $ttime;
$diffs[$interval]++;
// Create new temp time from time1 and interval
$ttime = strtotime("+1 " . $interval, $time1);
}
}
$count = 0;
$times = array();
// Loop thru all diffs
foreach ($diffs as $interval => $value) {
// Break if we have needed precission
if ($count >= $precision) {
break;
}
// Add value and interval
// if value is bigger than 0
if ($value > 0) {
// Add s if value is not 1
if ($value != 1) {
$interval .= "s";
}
// Add value and interval to times array
$times[] = $value . " " . $interval;
$count++;
}
}
// Return string with times
return implode(", ", $times);
}
?>
Now try this and see how it shows the difference...
echo dateDiff("2010-01-26", "2004-01-26") . "\n";
echo dateDiff("2006-04-12 12:30:00", "1987-04-12 12:30:01") . "\n";
echo dateDiff("now", "now +2 months") . "\n";
echo dateDiff("now", "now -6 year -2 months -10 days") . "\n";
echo dateDiff("2009-01-26", "2004-01-26 15:38:11") . "\n";

Categories