PHP Date difference - php

i've the following code:
$dStart = new DateTime('2013-03-15');
$dEnd = new DateTime('2013-04-01');
$dDiff = $dStart->diff($dEnd);
echo $dDiff->days;
I don't know why i'm getting 6015 as result.

Try like
$dStart = strtotime('2013-03-15');
$dEnd = strtotime('2013-04-01');
$dDiff = $dEnd - $dStart;
echo date('H:i:s',$dDiff);
or as per your code try with
$dDiff = $dStart->diff($dEnd);
$date->format('d',$dDiff);
echo $dDiff->days;
if you want diff in days try with this also
echo floor($dDiff/(60*60*24));

Try this-
$dStart = new DateTime('2013-03-15');
$dEnd = new DateTime('2013-04-01');
$dDiff = $dStart->diff($dEnd);
echo $dDiff->format('%d days')
Check PHP
Please check demo link

use this
$datetime1 = date_create('2013-03-15');
$datetime2 = date_create('2013-04-01');
$interval = date_diff($datetime1, $datetime2);
echo $interval->format('%R%a days');

I prefer something like:
function days_diff($first_date, $second_date)
{
$later = new DateTime($second_date);
$then = new DateTime($first_date);
return $later->diff($then)->format('a');
}

I got the same 6015 days on PHP 5.3.0 and found the solution using var_dump().
My exact code is here:
$timestring = "Thu, 13 Jun 2013 14:05:59 GMT";
date_default_timezone_set('GMT');
$date = DateTime::createFromFormat('D, d M Y G:i:s T', $timeString);
$nowdate = new DateTime("now");
$interval = $date->diff($nowdate);
Now if I do a var_dump($interval), the result is:
object(DateInterval)#5 (8) {
["y"]=>
int(0)
["m"]=>
int(0)
["d"]=>
int(0)
["h"]=>
int(19)
["i"]=>
int(45)
["s"]=>
int(33)
["invert"]=>
int(0)
["days"]=>
int(6015)
}
So the hours (h), minutes(i) and seconds (s) are set correctly but there is another property days which remains constant at 6015 and this is what others are getting as a bug. Well, I can't understand where it is getting this value. Again, as per the PHP manual for DateInterval at http://www.php.net/manual/en/class.dateinterval.php, I tried accessing them as properties of an object and things went absolutely fine.
Hence, I get exact result by:
echo (string) $interval->d." days ago";

Related

PHP wrong unix timestamp

find some problem when i was try to count days between two dates.
For fast debug my code i use http://sandbox.onlinephpfunctions.com/ with PHP version 7.4.0
Problem:
$date = new DateTime( '2018-02-28' );
$date2 = new DateTime( '2018-03-12' );
$diff = $date2->getTimestamp() - $date->getTimestamp();
var_dump($diff/(60*60*24)); //float(11.958333333333)
As you see - i set dates and calculated unixtimestamp-diff between dates.
Then i try find date when diff between two dates != 86400.
$date = new DateTime( '2020-03-08' );
$date2 = new DateTime( '2020-03-09' );
$diff = $date2->getTimestamp() - $date->getTimestamp();
var_dump($diff/(60*60*24)); //float(0.95833333333333)
Then i find all days from 2010 year:
$secInDay = 60 * 60 * 24;
$start_date = strtotime('2010-01-01');
$end_date = strtotime('2021-01-01');
while($start_date<$end_date) {
$next_date = strtotime('+1 day', $start_date);
$diff = ($next_date - $start_date) / $secInDay;
if ($diff !== 1) {
var_dump(date('d.m.Y', $start_date) . ' -> ' . date('d.m.Y', $next_date));
}
$start_date = strtotime('+1 day', $start_date);
}
Result:
string(24) "14.03.2010 -> 15.03.2010"
string(24) "07.11.2010 -> 08.11.2010"
string(24) "13.03.2011 -> 14.03.2011"
string(24) "06.11.2011 -> 07.11.2011"
string(24) "11.03.2012 -> 12.03.2012"
string(24) "04.11.2012 -> 05.11.2012"
string(24) "10.03.2013 -> 11.03.2013"
string(24) "03.11.2013 -> 04.11.2013"
string(24) "09.03.2014 -> 10.03.2014"
string(24) "02.11.2014 -> 03.11.2014"
string(24) "08.03.2015 -> 09.03.2015"
string(24) "01.11.2015 -> 02.11.2015"
string(24) "13.03.2016 -> 14.03.2016"
string(24) "06.11.2016 -> 07.11.2016"
string(24) "12.03.2017 -> 13.03.2017"
string(24) "05.11.2017 -> 06.11.2017"
string(24) "11.03.2018 -> 12.03.2018"
string(24) "04.11.2018 -> 05.11.2018"
string(24) "10.03.2019 -> 11.03.2019"
string(24) "03.11.2019 -> 04.11.2019"
string(24) "08.03.2020 -> 09.03.2020"
string(24) "01.11.2020 -> 02.11.2020"
So my main question - why PHP get wrong unix-timestamp for current dates?
Your algorithm finds the days for the changeover from winter/summer time and summer/winter time for the current time zone. These days have not 24 hours.
Russia no longer knows summer time. With
date_default_timezone_set('Europe/Moscow');
in the first line you get the result for your region. Try it self.
Update:
You get correct results with DateTime-Objects:
date_default_timezone_set('Europe/Moscow');
$diff = date_create('28.03.2010')->diff(date_create('29.03.2010'))->days;
echo $diff; //1
You can change the default UTC with this function:
date_default_timezone_set('America/Los_Angeles');
https://www.php.net/manual/en/function.date-default-timezone-set.php
Or directly edit your INI configuration file from your web server.
https://www.php.net/manual/en/datetime.configuration.php#ini.date.timezone
If you use the DateTime class like this and calculate the interval the leap year is catered for
function days_between( $start, $end )
{
// Put the 2 dates into DateTime objects
$start = new DateTime($start);
$end = new DateTime($end);
// Create a DateInterval object using diff() method
$interval = $end->diff($start);
// Format the result as an integer, representing number of days
return $interval->format('%a');
}
#not leap year
echo days_between('2019-02-27', '2019-02-27') . PHP_EOL; // 0
echo days_between('2019-02-27', '2019-02-28') . PHP_EOL; // 1
echo days_between('2019-02-27', '2019-02-29') . PHP_EOL; // 2 (there is no 29th
echo days_between('2019-02-27', '2019-03-01') . PHP_EOL; // 2
echo PHP_EOL;
#Leap Year
echo days_between('2020-02-27', '2020-02-27') . PHP_EOL; // 0
echo days_between('2020-02-27', '2020-02-28') . PHP_EOL; // 1
echo days_between('2020-02-27', '2020-02-29') . PHP_EOL; // 2
echo days_between('2020-02-27', '2020-03-01') . PHP_EOL; // 3
RESULT
0
1
2
2
0
1
2
3

PHP Date + days

I got something like this in MyBB and I want add 5 days to date ($datetime1) with one should be stored in $nowPlus5D.
Moreover display in $leeft variable how much days, hours, minutes left. difference between (day bought + 5days ) - datenow
define("IN_MYBB", 1);
require_once "global.php";
$data_zakupu = $db->query("
SELECT timestamp
FROM ".TABLE_PREFIX."subs
WHERE txn_id <> '' AND uid=".$mybb->user['uid']." ORDER BY lid DESC LIMIT 1;
");
$dat = $db->fetch_field($data_zakupu,"timestamp");
$date_buy = date('d-m-Y H:i:s', $dat); // added h:i:s
// Total bought
echo '<br><hr>';
echo 'Bought date - ' . $date_buy;
echo '<br>';
$datetime2 = new DateTime('now');
$datetime1 = new DateTime($date_buy);
$interval = $datetime1->diff($datetime2);
$nowPlus5D = $datetime1->add(new DateInterval('P5D'));
echo '<hr><br>';
echo 'Expiration date - ' . $nowPlus5D->format('%a days, %h hours, %i, minutes');
echo '<br>';
$leeft = $nowPlus5D->diff($datetime1);
var_dump($leeft);
echo '<br>';
echo $left->format('%a days, %h hours, %i, minutes');
and I got that
Bought date - 20-12-2018 18:20:48
Expiration date - %pm 25pm1848, %06 062018000000Tue, 25 Dec 2018 18:20:48 +010048, %20, 12201200000031Europe/Warsaw48
object(DateInterval)#14 (15) { ["y"]=> int(0) ["m"]=> int(0) ["d"]=> int(0) ["h"]=> int(0) ["i"]=> int(0) ["s"]=> int(0) ["weekday"]=> int(0) ["weekday_behavior"]=> int(0) ["first_last_day_of"]=> int(0) ["invert"]=> int(0) ["days"]=> int(0) ["special_type"]=> int(0) ["special_amount"]=> int(0) ["have_weekday_relative"]=> int(0) ["have_special_relative"]=> int(0) }
Fatal error: Call to a member function format() on integer in /stackoverflow.php on line 42
Your main issue is you are confusing a couple objects. Specifically DateInterval with DateTime. Formatting is one thing that differs.
<?php
$date_buy = '2018-12-15 10:05:22';
$datetime2 = new DateTime('now');
$datetime1 = new DateTime($date_buy);
$interval = $datetime1->diff($datetime2);
$nowPlus5D = $datetime1->add(new DateInterval('P5D'));
//THIS IS A DATETIME OBJECT, NOT AN INTERVAL! NOTE FORMAT `Y-m-d H:i:s`
echo 'Expiration date - ' . $nowPlus5D->format('d \d\a\y\s, H \h\o\u\r\s, i \m\i\n\u\t\e\s');
var_dump($nowPlus5D);
var_dump($datetime1);
// ^ Notice those are the same? A result of `$nowPlus5D = $datetime1->add(new DateInterval('P5D'));`
// and Intervals then are of course zeros...
$left = $nowPlus5D->diff($datetime1);
echo '<br>';
echo $left->format('%a days, %h hours, %i, minutes');
// could do this...
$left = $nowPlus5D->diff(new \DateTime);
echo $left->format('%a days, %h hours, %i, minutes');
Anyway, think your main confusion was over the two object types. Imagine you can take it from here.

Increment the day value from current day

For example, in my case, i already has this value of array.....
array(1) {
[1]=>
array(1120) {
["2006-02-25"]=>
array(1) {
[0]=>
int(33)
}
["2006-02-20"]=>
array(1) {
[0]=>
int(38)
}
["2006-02-28"]=>
array(1) {
[0]=>
int(46)
}
that result I've got this code
$explodeEndDate = explode(" ",$adEndDate);
$explodeStartDate = explode(" ", $adStartDate);
$StartDate = $explodeStartDate[0];
$NewStartDate = strtotime("$explodeStartDate[0]");
$NewEndDate = strtotime("$explodeEndDate[0]");
$timeDiff = abs($NewEndDate - $NewStartDate);
// 86400 seconds in one day
$NumberDays = $timeDiff/86400;
//convert into int
$NumberDays = intval($NumberDays);
if(array_key_exists($NumberDays, $array[$itemType]) == false){
$array[$itemType][$StartDate] =[$NumberDays];
}
}
what I wanted to achieve is, in the "$StartDate" value which is for example ["2006-02-28"] , I wanted to plus it with the value of it. If we referring back to the figure above for example is
["2006-02-25"]=>
array(1) {
[0]=>
int(33)
so 2006-02-25 is the plus by 33 and the result is 2006-04-01. and after that, i wanted to make the date within that range
If you want to add date so here you go:
Months:
<?php
$date = date('Y-m-d', strtotime("+33 months", strtotime('2006-02-25')));
var_dump($date)
?>
Demo.
Days:
<?php
$date = date('Y-m-d', strtotime("+33 days", strtotime('2006-02-25')));
var_dump($date)
?>
Demo

is it possible to use datetime in an array? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 8 years ago.
Improve this question
Is it possible to use DateTime to grab every date from now till one week ago and than make an array, for example
1-4-2014
1-3-2014
1-2-2014
And so on
Currently this is my code
<?php
$datetime = new DateTime();
$datetime->format('Y-m-d');
$arr = array(/* diverse dates */);
foreach ($to_remove as $item)
{
$is_smaller = ($to_remove->format('U') <= $datetime->format('U'));
if ($is_smaller)
{
$arr = array_filter($arr, function($item) use ($to_remove) {
return !preg_match("/$to_remove by /", $item);
});
}
}
Basically I need it to check the current date and the dates from one week ago and then remove the string from the array.
Yes, you can use DateTime class and DateInterval with DatePeriod:
$now = new DateTime( "now");
$yourInterval= new DateInterval( 'P1D'); //here you set interval per one day
$yourPeriodOfSevenDays= new DatePeriod( $now, $yourInterval, 7); // here you will set to what piriod of time get inerval
foreach($yourPeriodOfSevenDays as $day) {
$date = $day->format( 'd-m-Y');
$resultArray[] = $date ;
}
Now you will have all dates in array
array(8) { [0]=> string(10) "04-01-2014" [1]=> string(10) "05-01-2014" [2]=> string(10) "06-01-2014" [3]=> string(10) "07-01-2014" [4]=> string(10) "08-01-2014" [5]=> string(10) "09-01-2014" [6]=> string(10) "10-01-2014" [7]=> string(10) "11-01-2014" }
This is the simplest way I can think of:-
$lastWeek = new \DateTime('-7 days');
$interval = new \DateInterval('P1D');
$period = new \DatePeriod($lastWeek, $interval, new \DateTime());
var_dump(iterator_to_array($period));
See it working.
Even simpler, if you like one liners:-
$period = new \DatePeriod(new \DateTime('-7 days'), new \DateInterval('P1D'), new \DateTime());
var_dump(iterator_to_array($period));
See it working.
Then again, you can use a DatePeriod object in a foreach loop, so you may not need an array:-
$period = new \DatePeriod(new \DateTime('-7 days'), new \DateInterval('P1D'), new \DateTime());
foreach($period as $day){
echo $day->format('Y-m-d');
}
See it working
Reference http://php.net/datetime
You could use DateTime::add.
$dateTime = new DateTime("now");
$dateInterval = new DateInterval('P1D');
$days = 7;
$resultArray = array();
for($i=0 ; $i<$days ; $i++){
$dateTime->add($dateInterval);
$resultArray[] = $dateTime->format('d-m-Y');
}
Result:
array(7) {
[0]=> string(10) "05-01-2014"
[1]=> string(10) "06-01-2014"
[2]=> string(10) "07-01-2014"
[3]=> string(10) "08-01-2014"
[4]=> string(10) "09-01-2014"
[5]=> string(10) "10-01-2014"
[6]=> string(10) "11-01-2014"
}
Edit:
My fault, i overread the description "one week ago".
Also you can use DateTime::sub

Months from 2 unixtimestamps

I have 2 timestamps from 2 dates: 01/2012 and 02/2013. The difference between these timestamps is 31795200. The function i've used is:
function unixTimeStampInMonths($timestamp){
$elapsed_minutes = ($timestamp / 60);
$elapsed_hours = ($elapsed_minutes / 60);
$elapsed_days = ($elapsed_hours / 24);
$elapsed_months = floor($elapsed_days / 30);
return $elapsed_months;
}
But there is a problem, the months are rounded to 30 days. What's the best way of calculating the months difference between them?
LE:
The solution suggested by a friend is:
// arguments format: 05/2010
function monthDifferenceBetween2Dates($first, $second){
$expl1 = explode('/', $first);
$expl2 = explode('/', $second);
$months_in_years = ($expl2[1] - $expl1[1] - 1) * 12;
$first_months = 12 - $expl1[0];
$second_months = $expl2[0];
return $months_in_years + $first_months + $second_months;
}
i'm gonna use this. thanks #nickb
Use PHP's DateTime class instead of UNIX timestamps:
$start = DateTime::createFromFormat( 'm/d/Y', '01/01/2012');
$end = DateTime::createFromFormat( 'm/d/Y', '02/01/2013');
$diff = $start->diff( $end);
var_dump( $diff);
Will output:
object(DateInterval)#3 (8) {
["y"]=>
int(1)
["m"]=>
int(1)
["d"]=>
int(0)
["h"]=>
int(0)
["i"]=>
int(0)
["s"]=>
int(0)
["invert"]=>
int(0)
["days"]=>
int(397)
}
So, to calculate total months, we can do:
$months = $diff->y * 12 + $diff->m;
Which will print 13. Demo

Categories