What is the best (date format independent way) in PHP to calculate difference in days between two dates in specified format.
I tried the following function:
function get_date_offset($start_date, $end_date)
{
$start_time = strtotime($start_date);
$end_time = strtotime($end_date);
return round(($end_time-$start_time)/(3600*24));
}
It works ok on linux box, but when running under windows strtotime returns ''.
EDIT:
Input date is in mm/dd/yyyy format, but I would like to make it accept $format as a parameter.
I need only difference in days.
If you do not want or you cannot use Zend Framework or Pear package try this function i hope this would help:
function dateDifference($date1, $date2)
{
$d1 = (is_string($date1) ? strtotime($date1) : $date1);
$d2 = (is_string($date2) ? strtotime($date2) : $date2);
$diff_secs = abs($d1 - $d2);
$base_year = min(date("Y", $d1), date("Y", $d2));
$diff = mktime(0, 0, $diff_secs, 1, 1, $base_year);
return array
(
"years" => abs(substr(date('Ymd', $d1) - date('Ymd', $d2), 0, -4)),
"months_total" => (date("Y", $diff) - $base_year) * 12 + date("n", $diff) - 1,
"months" => date("n", $diff) - 1,
"days_total" => floor($diff_secs / (3600 * 24)),
"days" => date("j", $diff) - 1,
"hours_total" => floor($diff_secs / 3600),
"hours" => date("G", $diff),
"minutes_total" => floor($diff_secs / 60),
"minutes" => (int) date("i", $diff),
"seconds_total" => $diff_secs,
"seconds" => (int) date("s", $diff)
);
}
The PEAR Date class offers all kinds of features for finding the differences between dates and about 1000 other things as well. The docs for it are here...
The problem with PHP is that it doesn't have a definite DateTime type. You can use a Unix timestamp, or the built-in DateTime class, but they are pretty limited in their functionality. I expect that there should be some 3rd party classes with more extensive support for date-time calculations, but I haven't looked for it.
Using Unix timestamps for date (not time) calculations is also tricky. You'd have to discard the time part, but simply resetting to 00:00 is not safe because of daylight savings time (DST). DST has the effect that there are two days every year that don't have exactly 24 hours. Thus, when adding/subtracting dates you might end up with a value that does not divide evenly with 3600*24.
I'd suggest looking for some 3rd party class that has proper support for all this stuff. Date/Time calculations are awesome in their ugliness. :P
The Zend Framework has the class Zend_Date for dealing with "date math". It works around system specific timestamp limits by using the BCMath extension, or if that's not available limits the timestamps by max float value for your system.
// example printing difference in days
require('Zend/Date.php');
$date1 = new Zend_Date();
$date1->set(2, Zend_Date::MONTH);
$date1->set(27, Zend_Date::DAY);
$date1->set(2008, Zend_Date::YEAR);
$date2 = new Zend_Date();
$date2->set(3, Zend_Date::MONTH);
$date2->set(3, Zend_Date::DAY);
$date2->set(2008, Zend_Date::YEAR);
echo ($date2->getTimestamp() - $date1->getTimestamp()) / (3600*24);
I'm not sure what is considered best, since there is no built-in function in PHP for doing this, but some people have used gregoriantojd(), for example in this forum post.
gregoriantojd() gives the same results as using strtotime(), see this blogpost for how to do it:
http://www.phpro.org/examples/Calculate-Age-With-PHP.html
The following works for me. Believe I found it on the php.net docs somewhere.
*Edit - Woops, didn't see csl's post. This is the exact function from his link, must have been where I found it. ;)
//Find the difference between two dates
function dateDiff($startDate, $endDate)
{
// Parse dates for conversion
$startArry = date_parse($startDate);
$endArry = date_parse($endDate);
// Convert dates to Julian Days
$start_date = gregoriantojd($startArry["month"], $startArry["day"], $startArry["year"]);
$end_date = gregoriantojd($endArry["month"], $endArry["day"], $endArry["year"]);
// Return difference
return round(($end_date - $start_date), 0);
}
I was trying to calculate the difference of two dates for the purpose of showing the duration of an event. Most of the functions given on the problem fails if the event has a duration form friday at 17:00 to sunday at 15:00. My goal was to find the difference between the dates like:
date('Ymd',$end)-date('Tmd',$begining);
But that is likly to fail because there isn't 99 month in a year and 99 days in a month. I could convert the date string to UNIX timestamp and divide by 60*60*12, but some days have a greater or lesser number of hours, sometimes there's eaven a leap secound. So I made my own function using getdate() a function that returns an array of innformation about the timestamp.
/*
* datediff($first,$last)
* $first - unix timestamp or string aksepted by strtotime()
* $last - unix timestamp or string aksepted by strtotime()
*
* return - the difference in days betveen the two dates
*/
function datediff($first,$last){
$first = is_numeric($first) ? $first : strtotime($first);
$last = is_numeric($last ) ? $last : strtotime($last );
if ($last<$first){
// Can't calculate negative difference in dates
return -1;
}
$first = getdate($first);
$last = getdate($last );
// find the difference in days since the start of the year
$datediff = $last['yday'] - $first['yday'];
// if the years do not match add the appropriate number of days.
$yearCountedFrom = $first['year'];
while($last['year'] != $yearCountedFrom ){
// Take leap years into account
if( $yearCountedFrom % 4 == 0 && $yearCountedFrom != 1900 && $yearCountedFrom != 2100 ){
//leap year
$datediff += 366;
}else{
$datediff += 365;
}
$yearCountedFrom++;
}
return $datediff;
}
Concerning the GregorianToJD() function, it might work, but I feel a little bit uneasy since I do not understand how it work.
Let's not overengineer, guys.
$d1 = strtotime($first_date);
$d2 = strtotime($second_date);
$delta = $d2 - $d1;
$num_days = ($delta / 86400);
Calculate the difference between two Dates (and time) using Php. The following page provides a range of different methods (7 in total) for performing date / time calculations using Php, to determine the difference in time (hours, munites), days, months or years between two dates.
See Php Date Time - 7 Methods to Calculate the Difference between 2 dates
PHP 5.2 introduces the DateTime and DateInterval classes which makes this easy:
function get_date_offset($start_date, $end_date)
{
$start_time = new DateTime($start_date);
$end_time = new DateTime($end_date);
$interval = $end_time->diff($start_time);
return $interval->format('%a days');
}
Related
I have problem, I can't get time from personal identity number under 1970, I need to solve that, but using time. My function looks like. I don't know which way I can go. Thanks!
function getBirthDayFromRd($rd){
$day = substr($rd,4,2);
$month = substr($rd, 2,2);
$year = substr($rd, 0,2);
if($month>=51 and $month<=62){
$month = $month - 50;
}
$time = strtotime($day.".".$month.".".$year);
return date("d.m.Y", $time);
}
strtotime() fails due to its being tied to the Unix epoch which does not support dates prior to 1970. Just use DateTime which can handle pre-1970 dates and convert dates easily:
function getBirthDayFromRd($rd){
$date = DateTime::createFromFormat('ymd',$rd);
if($date->format('Y') > date("Y")) {
$date->modify('-100 years');
}
return $date->format('d.m.Y');
}
DateTime::createFromFormat() parses your date and creates the DateTime object. Then we just call DateTime::format() to format it in the desired format.
update
Just fixed a bug where pre-1970 dates were shown 100 years in the future.
Demo
I solve it another way, but u started me up.
if($year < 70){
$year = $year+1900;
$time = date_create_from_format("d.m.Y", $day.".".$month.".".$year);
return date_format($time, "d.m.Y");
}else{
$time = strtotime($day.".".$month.".".$year);
return date("d.m.Y", $time);
}
How exactly is this done? There's so many questions on stack-overflow about what I'm trying to do; However all of the solutions are to edit the MYSQL Query, and I need to do this from within PHP.
I read about the strtotime('-30 days') method on another question and tried it, but I can't get any results. Here's what I'm trying:
$current_date = date_create();
$current_date->format('U');
... mysql code ...
$transaction_date = date_create($affiliate['Date']);
$transaction_date->format('U');
if($transaction_date > ($current_date - strtotime('-30 days'))) {
} else if(($transaction_date < (($current_date) - (strtotime('-30 days'))))
&& ($transaction_date > (($current_date) - (strtotime('-60 days'))))) {
}
Effectively, I'm trying to sort all of the data in the database based on a date, and if the database entry was posted within the last 30 days, I want to perform a function, then I want to see if the database entry is older than 30 days, but not older than 60 days, and perform more actions.
This epoch math is really weird, you'd think that getting the epoch of the current time, the epoch of the data entry, and the epoch of 30 and 60 days ago would be good enough to do what I wanted, but for some reason it's not working, everything is returning as being less than 30 days old, even if I set the date in the database to last year.
No need to convert to unix timestamp, you can already compare DateTime objects:
$current_date = data_create();
$before_30_day_date = date_create('-30 day');
$before_60_day_date = date_create('-60 day');
$transaction_date = date_create($affiliate['Date']);
if ($transaction_date > $before_30_day_date) {
# transation date is between -30 day and future
} elseif ($transaction_date < $before_30_day_date && $transaction_date > $before_60_day_date) {
# transation date is between -60 day and -30 day
}
This creates (inefficiently, see my comment above) an object:
$current_date = date_create(date("Y-m-d H:i:s"));
From which you try to subtract an integer:
if($transaction_date > ($current_date - strtotime('-30 days'))) {
which is basically
if (object > (object - integer))
which makes no sense.
you're mixing the oldschool time() system, which deals purely with unix timestamps, and the newer DateTime object system, which deals with objects.
What you should have is
$current_date = date_create(); // "now"
$d30 = new DateInterval('P30D'); // 30 days interval
$transaction_date = date_create($affiliate['Date']);
if ($transaction_date > ($current_date->sub($d30)) { ... }
You might consider DatePeriod class, which in essence gives you the ability to deal with a seires of DateTime objects at specified intervals.
$current_date = new DateTime();
$negative_thirty_days = new DateInterval::createFromDateString('-30 day');
$date_periods = new DatePeriod($current_date, $negative_thrity_days, 3);
$thirty_days_ago = $date_periods[1];
$sixty_day_ago = $date_periods[2];
Here you would use $thirty_days_ago, $sixty_days_ago, etc. for your comparisons.
Just showing this as alternative to other options (which will work) as this is more scalable if you need to work with a larger number of interval periods.
I'm trying to use DateTime to check if a credit card expiry date has expired but I'm a bit lost.
I only want to compare the mm/yy date.
Here is my code so far
$expmonth = $_POST['expMonth']; //e.g 08
$expyear = $_POST['expYear']; //e.g 15
$rawExpiry = $expmonth . $expyear;
$expiryDateTime = \DateTime::createFromFormat('my', $rawExpiry);
$expiryDate = $expiryDateTime->format('m y');
$currentDateTime = new \DateTime();
$currentDate = $currentDateTime->format('m y');
if ($expiryDate < $currentDate) {
echo 'Expired';
} else {
echo 'Valid';
}
I feel i'm almost there but the if statement is producing incorrect results. Any help would be appreciated.
It's simpler than you think. The format of the datess you are working with is not important as PHP does the comparison internally.
$expires = \DateTime::createFromFormat('my', $_POST['expMonth'].$_POST['expYear']);
$now = new \DateTime();
if ($expires < $now) {
// expired
}
You can use the DateTime class to generate a DateTime object matching the format of your given date string using the DateTime::createFromFormat() constructor.
The format ('my') would match any date string with the string pattern 'mmyy', e.g. '0620'. Or for dates with 4 digit years use the format 'mY' which will match dates with the following string pattern 'mmyyyy', e.g. '062020'. It's also sensible to specify the timezone using the DateTimeZone class.
$expiryMonth = 06;
$expiryYear = 20;
$timezone = new DateTimeZone('Europe/London');
$expiryTime = \DateTime::createFromFormat('my', $expiryMonth.$expiryYear, $timezone);
See the DateTime::createFromFormat page for more formats.
However - for credit/debit card expiry dates you will also need to take into account the full expiry DATE and TIME - not just the month and year.
DateTime::createFromFormat will by default use todays day of the month (e.g. 17) if it is not specified. This means that a credit card could appear expired when it still has several days to go. If a card expires 06/20 (i.e. June 2020) then it actually stops working at 00:00:00 on 1st July 2020. The modify method fixes this. E.g.
$expiryTime = \DateTime::createFromFormat('my', $expiryMonth.$expiryYear, $timezone)->modify('+1 month first day of midnight');
The string '+1 month first day of midnight' does three things.
'+1 month' - add one month.
'first day of' - switch to the first day of the month
'midnight' - change the time to 00:00:00
The modify method is really useful for many date manipulations!
So to answer the op, this is what you need — with a slight adjustment to format to cater for single digit months:
$expiryMonth = 6;
$expiryYear = 20;
$timezone = new DateTimeZone('Europe/London');
$expiryTime = \DateTime::createFromFormat(
'm-y',
$expiryMonth.'-'.$expiryYear,
$timezone
)->modify('+1 month first day of midnight');
$currentTime = new \DateTime('now', $timezone);
if ($expiryTime < $currentTime) {
// Card has expired.
}
An addition to the above answers.
Be aware that by default the days will also be in the calculation.
For example today is 2019-10-31 and if you run this:
\DateTime::createFromFormat('Ym', '202111');
It will output 2021-12-01, because day 31 does not exist in November and it will add 1 extra day to your DateTime object with a side effect that you will be in the month December instead of the expected November.
My suggestion is always use the day in your code.
For op's question:
$y=15;
$m=05;
if(strtotime( substr(date('Y'), 0, 2)."{$y}-{$m}" ) < strtotime( date("Y-m") ))
{
echo 'card is expired';
}
For others with full year:
$y=2015;
$m=5;
if(strtotime("{$y}-{$m}") < strtotime( date("Y-m") ))
{
echo 'card is expired';
}
Would it not be simpler to just compare the string "201709" to the current year-month? Creating datetime objects will cost php some effort, I suppose.
if($_POST['expYear']. str_pad($_POST['expMonth'],2,'0', STR_PAD_LEFT ) < date('Ym')) {
echo 'expired';
}
edited as Adam states
The best answer is provided by John Conde above. It it does the minimum amount of processing: creates two correct DateTime objects, compares them and that's all it needs.
It could work also as you started but you must format the dates in a way that puts the year first.
Think a bit about it: as dates, 08/15 (August 2015) is after 12/14 (December 2014) but as strings, '08 15' is before '12 14'.
When the year is in front, even as strings the years are compared first and then, only when the years are equal the months are compared:
$expiryDate = $expiryDateTime->format('y m');
$currentDate = $currentDateTime->format('y m');
if ($expiryDate < $currentDate) {
echo 'Expired';
} else {
echo 'Valid';
}
Keep it simple, as the answer above me says except you need to string pad to the left:
isCardExpired($month, $year)
{
$expires = $year.str_pad($month, 2, '0', STR_PAD_LEFT);
$now = date('Ym');
return $expires < $now;
}
No need to add extra PHP load using DateTime
If you are using Carbon, which is a very popular Datetime extension library. Then this should be:
$expMonth = $_POST['month'];
$expYear = $_POST['year'];
$format_m_y = str_pad($expMonth,2,'0', STR_PAD_LEFT).'-'.substr($expYear, 2);
$date = \Carbon\Carbon::createFromFormat('m-y', $format_m_y)
->endOfMonth()
->startOfDay();
if ($date->isPast()) {
// this card is expired
}
Also take into consideration the exact date and time expiration:
Credit cards expire at the end of the month printed as its expiration date, not at the beginning. Many cards actually technically expire one day after the end of that month. In any case, unless they list a specific day of expiration along with month and year, they should work all the way through the end of their expiration month. Cardholders should not wait until the last moment to secure a replacement card. Source
$bought_months = 6;
$currentDate = date('Y-m-d');
$expiring = strtotime('+'.$bought_months.' month', $currentDate);
This is what i tried.
I am trying to get a unix timestamp value of 6 months ahead from today.
How can i add months to my unix timestamp right? I tried above, since my other thought - calculating by seconds like one month in seconds: 2 629 743.83 * how many months + current timestamp, will not be precise.
(ofcourse because months have different number of days)
I get "A non well formed numeric value encountered" for the code above.
How can i do this?
Since you are using the current timestamp, you can omit the $currentDate variable altogether and it should make the notice go away too.
$bought_months = 6;
$expiring = strtotime('+'.$bought_months.' month');
To make the date correctly you'd need to use something like:
mktime( 0, 0, 0, ( $month + 6 ), $day, $year );
For maximum compatibility with post-2038 dates, use php's builtin DateTime class:
$d = new DateTime();
$d->modify("+6 months");
echo $d->format("U");
I have two times in PHP and I would like to determine the elapsed hours and minutes. For instance:
8:30 to 10:00 would be 1:30
A solution might be to use strtotime to convert your dates/times to timestamps :
$first_str = '8:30';
$first_ts = strtotime($first_str);
$second_str = '10:00';
$second_ts = strtotime($second_str);
And, then, do the difference :
$difference_seconds = abs($second_ts - $first_ts);
And get the result in minutes or hours :
$difference_minutes = $difference_seconds / 60;
$difference_hours = $difference_minutes / 60;
var_dump($difference_minutes, $difference_hours);
You'll get :
int 90
float 1.5
What you now have to find out is how to display that ;-)
(edit after thinking a bit more)
A possibility to display the difference might be using the date function ; something like this should do :
date_default_timezone_set('UTC');
$date = date('H:i', $difference_seconds);
var_dump($date);
And I'm getting :
string '01:30' (length=5)
Note that, on my system, I had to use date_default_timezone_set to set the timezone to UTC -- else, I was getting "02:30", instead of "01:30" -- probably because I'm in France, and FR is the locale of my system...
You can use the answer to this question to convert your times to integer values, then do the subtraction. From there you'll want to convert that result to units-hours-minutes, but that shouldn't be too hard.
Use php timestamp for the job :
echo date("H:i:s", ($end_timestamp - $start_timestamp));
$d1=date_create()->setTime(8, 30);
$d2=date_create()->setTime(10, 00);
echo $d1->diff($d2)->format("%H:%i:%s");
The above uses the new(ish) DateTime and DateInterval classes. The major advantages of these classes are that dates outside the Unix epoch are no longer a problem and daylight savings time, leap years and various other time oddities are handled.
$time1='08:30';
$time2='10:00';
list($h1,$m1) = explode(':', $time1);
list($h2,$m2) = explode(':', $time2);
$time_diff = abs(($h1*60+$m1)-($h2*60+$m2));
$time_diff = floor($time_diff/60).':'.floor($time_diff%60);
echo $time_diff;