PHP if date is older than X days - php

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

Related

How to get current datetime in order to compare with other date in a specif datetime

I need to compare a datetime field called "last_power" to a specific range time that starts at 7AM every day.
For example:
Day starts at 7AM.
NOW() = 2022/12/15 02:40:40 PM || last_power is setting to 2022/12/14 06:40:40 PM -> true
NOW() = 2022/12/15 02:40:40 PM || last_power is setting to 2022/12/15 11:40:40 AM -> false
I'm stucked when "last_power" is between midnight and 6:59 AM.
NOW() = 2022/12/15 12:40:40 AM || last_power is setting to 2022/12/14 01:40:40 AM -> SHOULD BE true because in my code "2022/12/15 12:40:40 AM" is < 7AM of today, but the result give me a false result.
//set
$current = time();
$new_day = strtotime('today 7:00');
$date_power = strtotime($last_power);
if ($current - $date_power >= (24 * 60 * 60) ||
($date_power < $new_day && $current >= $new_day))
{
echo "true";
//last_result < today 7:00AM -> you award your price
} else {
echo "false";
//last_result > today 7:00AM -> you have already received the price for today
}
The trick is to determine the correct cutoff time or correct date for the cutoff. This is much easier with the DateTime object.
$last_power = 'yesterday 7:00:01';
$current = new DateTime('today 6:59:59'); // demo, for production use: new DateTime('now')
$new_day = new DateTime('today 7:00'); // can be past or future
$date_power = new DateTime($last_power); // you may need to use: (new DateTime())->createFromFormat()
if($current < $new_day){ // prior to 7am
$new_day->modify('-1day'); // adjust the cutoff date
}
// now a simple comparison
if($date_power < $new_day){
echo "true, price is older than " .$new_day->format('Y-m-d, H:i:s');
}else{
echo "false, price is same age or newer than " .$new_day->format('Y-m-d, H:i:s');
}
The above will output the following (today being 2022-12-16):
false, price is newer than 2022-12-15, 07:00:00
Run it live here.
using the DateTime builtin class makes life quite easy here
$power_date = '12/16/2022 02:40:40 PM';
$power_d = (new DateTime())->createFromFormat('m/d/Y H:i:s a', $power_date);
echo 'power_date = ' . $power_d->format('d/m/Y H:i:s');
echo PHP_EOL;
$valid_end = new DateTime('today 07:00:00');
echo 'Valid End Date time = ' . $valid_end->format('d/m/Y H:i:s');
echo PHP_EOL;
$valid_start = new DateTime('yesterday 07:00:00');
echo 'Valid Start Date time = ' . $valid_start->format('d/m/Y H:i:s');
echo PHP_EOL;
if ( $power_d > $valid_start && $power_d < $valid_end) {
echo 'VALID';
} else {
echo 'INVALID';
}

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);
}

Working dates between two given dates in Php

Please, i need assistance in this code.I have checked others in Stakeoverflow, but it is not combatible, hence this question. I want to generate all working /weekdays between two dates.I have found a code, but it is generating all days, including weekend. How do i eliminate the weekend from the list or ensure the list generated is ONLY for weekdays?
<?php
$start_Date = date('Y-m-d');
$end_Date = date('Y-m-d', strtotime('30 weekdays'));
//echo $start_Date."<br/>";
//echo $end_Date."<br/>";
// Specify the start date. This date can be any English textual format
$date_from = $start_Date;
$date_from = strtotime($date_from); // Convert date to a UNIX timestamp
// Specify the end date. This date can be any English textual format
$date_to = $end_Date;
$date_to = strtotime($date_to); // Convert date to a UNIX timestamp
// Loop from the start date to end date and output all dates inbetween
$c = 0;
for ($i = $date_from; $i <= $date_to; $i += 86400) {
$c++;
echo $c . "=> " . date("Y-m-d", $i) . '<br />';
}
I expect 30days to be generated but with this code, I am getting 42days . Weekend has been added,instead of weekdays ONLY .
Just add this to your loop:
$w = date('w',$i);// day of week - Sunday == 0, Saturday == 6
if($w == 0 || $w == 6){
continue;
}
DEMO
Your code is almost working only have to add a if checking in your code
your code
for ($i = $date_from; $i <= $date_to; $i += 86400) {
$c++;
echo $c . "=> " . date("Y-m-d", $i) . '<br />';
}
please replace with that one
for ($i = $date_from; $i <= $date_to; $i += 86400) {
$day = date("w", $i);
if($day != 0 && $day!= 6){ // will continue if not Sunday or Saturday
$c++;
echo $c . "=> " . date("Y-m-d", $i) . '<br />';
}
}
You also can take help from php.net
Thanks
You may need to get the day of the week, like date("D"), then use it in your for loop to check..something like this?:
$Weekends = array("Sat","Sun");
for....
$DayOfWeek = date("D",$i);
if(!in_array($DayOfWeek, $Weekend)){
// increment...
}

Show content based on date (date before, date after, date between)

This is setup to show a button between 2 dates set. And to show a "Sign up starts at xxx" before the set start up date, and "Sign up closed the xxxx" after the set end date...
Somehow nothing shows for the "active periode" / the dates in betweeen...
$DateToday = date('Ymd');
$DateStart = get_field('pamelding_fra');
$DateEnd = get_field('pamelding_slutt');
$DateStartOut = new DateTime($DateStart);
$DateEndOut = new DateTime($DateEnd);
if ($DateStart >= $DateToday){
$ClassStatus = "<div class=\"OpenClassButton\"><span class=\"ClassFullWarning\">Påmeldingen åpner " . $DateStartOut->format('j M Y') . "</span></div>";
$ClassButton = $ClassStatus;
}elseif ($DateEnd <= $DateToday){
$ClassStatus = "<div class=\"OpenClassButton\"><span class=\"ClassFullWarning\">Påmeldingen stengte " . $DateEndOut->format('j M Y') . "</span></div>";
$ClassButton = $ClassStatus;
}elseif ($DateStart <= $DateToday && $DateEnd >= $DateToday){
//Do some stuff - show button, this is the active time.
}
Might not be best-practice and I might make stuff difficult for me, suggestions appriciated.
Don't compare dates using date strings. If they are in different formats (like Ymd, mdY etc) you will get unwanted results. Use unix timestamps instead.
$today = time(); // Get today's timestamp
if ($today < strtotime($DateStart)) {
// Do stuff before
} elseif ($today > strtotime($DateEnd)) {
// Do stuff after
} else {
// Active. No need for any conditions here,
// since we only have three states.
}

Compare h:i:s to see which hour is greater including midnight - PHP

Okay so I have a function that compares the hours from 00:00:00 - 24:00:00 to tell the closing time. Now the issue I have is, lets say the store opens at 8AM and closes at midnight, well 00:00:00is going to be less than 23:00:00. How would I go about making sure that it recognizes that midnight is greater?
Here is what I am doing:
if((strtotime($openTime) < time()) && (strtotime($closeTime) > time()))
{
$response['data_retrieved']['store'][$i]['store_settings']['open'] = 1;// open
}
else
{
$response['data_retrieved']['store'][$i]['store_settings']['open'] = 0; //close
}
Suggestions?
Since there is no 24:00:00, you'll need the full date string Y-m-d H:i:s to do an accurate comparison.
Even just adding in the date won't be enough, as it will break when looking at the last day of the month ('31 08:00:00' < '1 00:00:00').
PHP has a very good DateTime support. Its better to use that instead of reinventing things. Also like #mopo922 suggested, you'll need the full Y-m-d H:i:s
The answer #mopo922 provided above is the most foolproof and most correct answer.
Another method would be to "add" 24 hours to the $closeTime if $startTime > $closeTime. It's quite dodgy but still solves the problem.
<?php
date_default_timezone_set('Australia/Sydney');
$openTime = strtotime('08:00');
$currentTime = strtotime('23:00');
$closeTime = strtotime('10:00');
echo 'open: ' .$openTime . '<br>' .
'time(): ' . $currentTime . '<br>' .
'close: ' . $closeTime . '<br>';
// 1 day = 86400 seconds
if ($closeTime < $openTime) {
$closeTime += 86400;
}
if($openTime < $currentTime && $closeTime > $currentTime)
{
echo 'open';
}
else
{
echo 'closed';
}
?>

Categories