Check how many days were passed since the last update in PHP - php

I am trying to check how many days were passed since the user last entered the system. I get the last time he\she entered from mysql table column (datetime). so I wrote :
$user_last_visit = $user_info['last_updated']; // 2013-08-08 00:00:00
$user_last_visit_str = strtotime($user_last_visit); // 1375912800
$today = strtotime(date('j-m-y')); // 1250114400
$diff = $today - $user_last_visit_str;
Where $user_info['last_updated'] has the last time he\she visited with the value of 2013-08-08 00:00:00.
After strtotime I get $user_last_visit_str equals to 1375912800
$today has the value of 9-08-13 and after strtotime I get 1250114400.
Some reason $diff = $today - $user_last_visit_str; is negative instead of getting a positive value with 24*60*60*1000 (one day = 24*60*60*1000 ms).
Any ideas?

A simple solution using diff:
echo date_create()->diff(date_create($user_last_visit))->days;
If all else fails, just do:
$diff = floor((time() - $user_last_visit_str) / (60 * 60 * 24));

you can use below code to get date diff, here i given static last date which is 15th july 2013, and taking different from current date.
$last_date = date('y-m-d', strtotime('15th july 2013'));//here give your date as i mentioned below
//$last_date = date('y-m-d', strtotime($your_old_date_val));
$current_date = date('y-m-d');//
echo $date_diff = strtotime($current_date) - strtotime($last_date) ;
echo $val = 60*60*24;
$days_diff = $date_diff / $val;
echo $days_diff;

Try this:
$user_last_visit = $user_info['last_updated']; // considering the value of user last visit is 2013-08-08 00:00:00 which indicates year, month, day, hour, minute, second respectiveliy
$user_last_visit_str = strtotime($user_last_visit);
$today = time();
$diff = $today - $user_last_visit_str;
$no_of_days = ($diff / (60*60*24));

Try using a DateTime object if your version of PHP supports it:
$user_last_visit = DateTime::createFromFormat('Y-m-d H:i:s', $user_info['last_updated']);
$today = new DateTime();
$diff = $today->diff( $user_last_visit, true );
echo $diff->days;
$diff will be a DateInterval object.

try reversing the $today assignment, like so:
$today = strtotime(date('y-m-j'));
that worked for me.

Related

Subtracting days from a date using PHP

I am trying to subtract X days from a date retrieved from MySQL.
X is a variable that can be any integer.
I tried:
$days = trim(explode("days",explode("Order will be late by",$resPO['EXCEPTION_MSG'])[1])[0]); // returning a number 1, 2, 3, etc
$date = $resPO['DUE_DESIRED_RECV_DATE']; //date from database
$reqdate = date('Y-m-d', strtotime("-$days days", strtotime($date)));
Resulting: 04/30/2021
No matter what the date is inserted into the formula. HOWEVER, when I manually change the formula to a constant, it does calculate properly.
Example:
$reqdate = date('Y-m-d', strtotime("-3 days", strtotime($date)));
EDIT:
The $days is working fine when I use a manual date like "2021-04-30". So, looks like the problem is the date I am getting from MySQL.
It is set as DATE and is printing properly.
EDIT 2:
// FORMATTING DATE
$days = $resPO['ORDER_PROJ_LATE_BY'];
//$days = 3;
$date = $resPO['DUE_DESIRED_RECV_DATE']; //date from database
$new_date = explode("-",$date);
$var_new_date = date("Y-m-d", mktime(0,0,0,$new_date[1],$new_date[2] - $days,$new_date[0]));
$newdate = date('Y-m-d', strtotime("-$days days", strtotime($var_new_date)));
EDIT 3:
I found a workaround by multiplying the DAYS (int) from MySQL by 3 and then dividing the results by 3.1 (closer as possible to 3).
// FORMATTING DATE
$days = $resPO['ORDER_PROJ_LATE_BY'];
$days = ($days * 3)/3.1;
Any help?
your code is alright, can it be that the date read from MySQL - in $resPO['DUE_DESIRED_RECV_DATE'] - has an unconventional formatting? strtotime expects them to be formatted in one of the recognized formats.
$days = 3;
$date = '2021-05-01';
$reqdate = date('Y-m-d', strtotime("-$days days", strtotime($date)));
echo "$reqdate\n";
returns
2021-04-28

PHP Current time in Hour:Minutes

I want to have have 2 variables with the current time in hours:minutes and also one that has +15 minutes. But first I must also add +6 hours.
So for example, right now it is 2018-01-07 16:35:10. So first I add +6 hours. So it will be 2018-01-07 22:35:10. Next, I want to extract only the hours:minutes.
I want to get only "22:35" to variable.
And next variable, I want 22:35 +15 minutes, so 22:50.
So I have $dateNow = 22:35 and $dateThen = 22:50
I have tried this so far to get current time now and +6 hours, but it's not working. Error: Call to a member function format() on integer
$now = strtotime(date("Y-m-d H:i:s")." +6 hours");
$then = $now->format('H:i');
echo $then;
i think in this case it would be very use full to use the DateTime class from PHP. The Problem with your code is strtotime returns a int not an DateTime object.
I've modified your code so it will work:
$org = new DateTime("2018-01-07 16:35:10");
$then = $org->add(new DateInterval("PT6H"));
echo $then->format("H:i"),"<br>";
$afterThen = $then->add(new DateInterval("PT15M"));
echo $afterThen->format("H:i");
Short solution with DateTime and DateInterval objects:
$now = new DateTime();
$result = $now->add(new DateInterval('PT6H15M'))->format('H:i');
Try this:
$time = time() + 3600 * 6; // add 6 hours
$date = date("H:i", $time); // format date
$date_plus_15 = date("H:i", $time + 60 * 15); // format date and add 15 minutes
echo "Time: {$date} <br>";
echo "Time + 15 mins: {$date_plus_15}";
Example here: https://ideone.com/ZR6cfy

Calculating time difference for fixed hour

I want to calculate the time difference from now (lets say 18:30:00) till this evening at 20pm.
$today = date('Y-m-d', time());
$remain = strtotime($today. " 00:00:00 + 20 hours") - time();
$remain = date('H:i:s', $remain);
I get a result which is one hour larger (02:30:00) than the actual result (01:30:00). I tried setting time zones but it's always the same result.
Using the DateTime object, you can do this easily:
$d1 = new DateTime('2015-04-23 18:30');
$d2 = new DateTime('2015-04-23 20:00');
$interval = $d2->diff($d1);
echo $interval->format('%H:%i hours');

how to check if a date is three days before today

Hey i would like to know if there is any script (php) that could check if a specified date three days before today.
say..
$d1 = date("Y-m-d", filemtime($testfile));
$d2 = date("Y-m-d");
now i would like to know how to compare this two dates to check if d1 is atleast 3days ago or before d2
any help would be gladly appreciated.
Why not to use DateTime object.
$d1 = new DateTime(date('Y-m-d',filemtime($testfile));
$d2 = new DateTime(date('Y-m-d'));
$interval = $d1->diff($d2);
$diff = $interval->format('%a');
if($diff>3){
}
else {
}
Assuming you wish to test whether the file was modified more than three days ago:
if (filemtime($testfile) < strtotime('-3 days')) {
// file modification time is more than three days ago
}
Just check it with timestamp:
if (time() - filemtime($testfile) >= 3 * 86400) {
// ...
}
use date("Y-m-d", strtotime("-3 day")); for specific date
you can also use
strtotime(date("Y-m-d", strtotime("-3 day")));
to convert it to integer before comparing a date string
well, stunned to see no one is using mktime() function,
it makes the job simple
for example your input date is :10/10/2012
mktime convert it to unix time stamp
$check_date=mktime(0,0,0,10,**10+3**,2012);
we can perform any operations weather +,-,*,/
use timestamp instead of date,
$d1 = filemtime($testfile);
$now = time();
if ($now - $d1 > 3600*24*3) {
..
}

Given a Unix timestamp, how to get beginning and end of that day?

I have a Unix timestamp like this:
$timestamp=1330581600
How do I get the beginning of the day and the end of the day for that timestamp?
e.g.
$beginOfDay = Start of Timestamp's Day
$endOfDay = End of Timestamp's Day
I tried this:
$endOfDay = $timestamp + (60 * 60 * 23);
But I don't think it'll work because the timestamp itself isn't the exact beginning of the day.
strtotime can be used to to quickly chop off the hour/minutes/seconds
$beginOfDay = strtotime("today", $timestamp);
$endOfDay = strtotime("tomorrow", $beginOfDay) - 1;
DateTime can also be used, though requires a few extra steps to get from a long timestamp
$dtNow = new DateTime();
// Set a non-default timezone if needed
$dtNow->setTimezone(new DateTimeZone('Pacific/Chatham'));
$dtNow->setTimestamp($timestamp);
$beginOfDay = clone $dtNow;
$beginOfDay->modify('today');
$endOfDay = clone $beginOfDay;
$endOfDay->modify('tomorrow');
// adjust from the start of next day to the end of the day,
// per original question
// Decremented the second as a long timestamp rather than the
// DateTime object, due to oddities around modifying
// into skipped hours of day-lights-saving.
$endOfDateTimestamp = $endOfDay->getTimestamp();
$endOfDay->setTimestamp($endOfDateTimestamp - 1);
var_dump(
array(
'time ' => $dtNow->format('Y-m-d H:i:s e'),
'start' => $beginOfDay->format('Y-m-d H:i:s e'),
'end ' => $endOfDay->format('Y-m-d H:i:s e'),
)
);
With the addition of extended time in PHP7, there is potential to miss a second if using $now <= $end checking with this.
Using $now < $nextStart checking would avoid that gap, in addition to the oddities around subtracting seconds and daylight savings in PHP's time handling.
Just DateTime
$beginOfDay = DateTime::createFromFormat('Y-m-d H:i:s', (new DateTime())->setTimestamp($timestamp)->format('Y-m-d 00:00:00'))->getTimestamp();
$endOfDay = DateTime::createFromFormat('Y-m-d H:i:s', (new DateTime())->setTimestamp($timestamp)->format('Y-m-d 23:59:59'))->getTimestamp();
First a DateTime object is created and the timestamp is set to the desired timestamp. Then the object is formatted as a string setting the hour/minute/second to the beginning or end of the day. Lastly, a new DateTime object is created from this string and the timestamp is retrieved.
Readable
$dateTimeObject = new DateTime();
$dateTimeObject->setTimestamp($timestamp);
$beginOfDayString = $dateTimeObject->format('Y-m-d 00:00:00');
$beginOfDayObject = DateTime::createFromFormat('Y-m-d H:i:s', $beginOfDayString);
$beginOfDay = $beginOfDayObject->getTimestamp();
We can get the end of the day in an alternate manner using this longer version:
$endOfDayObject = clone $beginOfDayOject(); // Cloning because add() and sub() modify the object
$endOfDayObject->add(new DateInterval('P1D'))->sub(new DateInterval('PT1S'));
$endOfDay = $endOfDayOject->getTimestamp();
Timezone
The timezone can be set as well by adding a timestamp indicator to the format such as O and specifying the timestamp after creating the DateTime object:
$beginOfDay = DateTime::createFromFormat('Y-m-d H:i:s O', (new DateTime())->setTimezone(new DateTimeZone('America/Los_Angeles'))->setTimestamp($timestamp)->format('Y-m-d 00:00:00 O'))->getTimestamp();
Flexibility of DateTime
We can also get other information such as the beginning/end of the month or the beginning/end of the hour by changing the second format specified. For month: 'Y-m-01 00:00:00' and 'Y-m-t 23:59:59'. For hour: 'Y-m-d H:00:00' and 'Y-m-d H:59:59'
Using various formats in combination with add()/sub() and DateInterval objects, we can get the beginning or end of any period, although some care will need to be taken to handle leap years correctly.
Relevant Links
From the PHP docs:
DateTime
date with info on the format
DateTimeZone
DateInterval
You can use a combination of date() and mktime():
list($y,$m,$d) = explode('-', date('Y-m-d', $ts));
$start = mktime(0,0,0,$m,$d,$y);
$end = mktime(0,0,0,$m,$d+1,$y);
mktime() is smart enough to wrap months/years when given a day outside the specified month (jan 32nd will be feb 1st, etc)
You could convert the time to the current data and then use the strtotime function to find the start of the day and simply add 24 hours to that to find the end of the day.
You could also use the remainder operator (%) to find the nearest day. For example:
$start_of_day = time() - 86400 + (time() % 86400);
$end_of_day = $start_of_day + 86400;
The accepted answer unfortunately breaks due to a php bug that occurs in very specific scenarios. I'll discuss those scenarios, but first the answer using DateTime. The only difference between this and the accepted answer occurs after the // IMPORTANT line:
$dtNow = new DateTime();
// Set a non-default timezone if needed
$dtNow->setTimezone(new DateTimeZone('America/Havana'));
$dtNow->setTimestamp($timestamp);
$beginOfDay = clone $dtNow;
// Go to midnight. ->modify('midnight') does not do this for some reason
$beginOfDay->modify('today');
// now get the beginning of the next day
$endOfDay = clone $beginOfDay;
$endOfDay->modify('tomorrow');
// IMPORTANT
// get the timestamp
$ts = $endOfDay->getTimestamp();
// subtract one from that timestamp
$tsEndOfDay = $ts - 1;
// we now have the timestamp at the end of the day. we can now use that timestamp
// to set our end of day DateTime
$endOfDay->setTimestamp($tsEndOfDay);
So you'll note that instead of using ->modify('1 second ago'); we instead get the timestamp and subtract one. The accepted answer using modify should work, but breaks because of php bug in very specific scenarios. This bug occurs in timezones that change daylight savings at midnight, on the day of the year that clocks are moved "forward". Here is an example you can use to verify that bug.
bug example code
// a time zone, Cuba, that changes their clocks forward exactly at midnight. on
// the day before they make that change. there are other time zones which do this
$timezone = 'America/Santiago';
$dateString = "2020-09-05";
echo 'the start of the day:<br>';
$dtStartOfDay = clone $dtToday;
$dtStartOfDay->modify('today');
echo $dtStartOfDay->format('Y-m-d H:i:s');
echo ', '.$dtStartOfDay->getTimestamp();
echo '<br><br>the start of the *next* day:<br>';
$dtEndOfDay = clone $dtToday;
$dtEndOfDay->modify('tomorrow');
echo $dtEndOfDay->format('Y-m-d H:i:s');
echo ', '.$dtEndOfDay->getTimestamp();
echo '<br><br>the end of the day, this is incorrect. notice that with ->modify("-1 second") the second does not decrement the timestamp by 1:<br>';
$dtEndOfDayMinusOne = clone $dtEndOfDay;
$dtEndOfDayMinusOne->modify('1 second ago');
echo $dtEndOfDayMinusOne->format('Y-m-d H:i:s');
echo ', '.$dtEndOfDayMinusOne->getTimestamp();
echo '<br><br>the end of the day, this is correct:<br>';
$dtx = clone $dtEndOfDay;
$tsx = $dtx->getTimestamp() - 1;
$dty = clone $dtEndOfDay;
$dty->setTimestamp($tsx);
echo $dty->format('Y-m-d H:i:s');
echo ', '.$tsx;
bug example code output
the start of the day:
2020-03-26 00:00:00, 1585173600
the start of the *next* day:
2020-03-27 01:00:00, 1585260000
the end of the day, this is incorrect. notice that with ->modify("1 second ago") the
second does not decrement the timestamp by 1:
2020-03-27 01:59:59, 1585263599
the end of the day, this is correct:
2020-03-26 23:59:59, 1585259999
Today Starting date timestamp. Simple
$stamp = mktime(0, 0, 0);
echo date('m-d-Y H:i:s',$stamp);
$start_of_day = floor (time() / 86400) * 86400;
$end_of_day = ceil (time() / 86400) * 86400;
If your need both values in the same script. It is faster to +/- 86400 seconds to one of the variables than to fire both floor and ceil. For example:
$start_of_day = floor (time() / 86400) * 86400;
$end_of_day = $start_of_day + 86400;
For anyone that have this question in the future:
Any day code
<?php
$date = "2015-04-12 09:20:00";
$midnight = strtotime("midnight", strtotime($date));
$now = strtotime($date);
$diff = $now - $midnight;
echo $diff;
?>
Current day code
<?php
$midnight = strtotime("midnight");
$now = date('U');
$diff = $now - $midnight;
echo $diff;
?>
$date = (new \DateTime())->setTimestamp(1330581600);
echo $date->modify('today')->format('Y-m-d H:i:s'); // 2012-02-29 00:00:00
echo PHP_EOL;
echo $date->modify('tomorrow - 1 second')->format('Y-m-d H:i:s'); // 2012-02-29 23:59:59
$startOfDay = new \DateTime('tomorrow');
$startOfDay->modify('-1 day');
This works for me :)
A little late to the party, but here's another easy way to achieve what you're looking for:
$timestamp=1330581600;
$format = DATE_ATOM;
$date = (new DateTime())->setTimestamp($timestamp);
// Here's your initial date, created from the timestamp above
// 2012-03-01T06:00:00+00:00
$dateFromTimestamp = $date->format($format);
// This is the beginning of the day
// 2012-03-01T00:00:00+00:00
$startOfDay = $date->setTime(0,0);
// This is the beginning of the next day
// 2012-03-02T00:00:00+00:00
$startOfNextDay = $startOfDay->modify('+1 day');
I would personally avoid using the end of the day unless it's absolutely necessary. You can, of course, use 23:59:59 but this is not the actual end of the day (there's still 1 second left). What I do is use the start of the next day as my end boundary, for example:
$start = new DateTime('2021-11-09 00:00:00');
$end = new DateTime('2021-11-10 00:00:00');
if ($someDateTime >= $start && $someDateTime < $end) {
// do something
}
If I must use the end of the day, I'd go with calculating the start of the next day and then subtracting 1 microsecond from that.
$beginOfDay = (new DateTime('today', new DateTimeZone('Asia/Tehran')))->getTimestamp();
$endOfDay = $beginOfDay + 86399;
You can set a timezone by replacing "Asia/Tehran". One day is 86400 seconds, Don't ask me why 86399, It is a whisper in my mind that says it is 86399, So I do not even want to think about its truth.

Categories