PHP get time period by timestamp - php

How can I get the time period (day, week, month) by a given timestamp? I do not want the date. I want the next time period based on the amount of seconds.
Is there a PHP native function for that?
Example:
$period = getTimeperiod( 15638400 );
My attempt: I could check and count the seconds:
if x <= 60 => min
if x <= 60*60 => hour
if x <= 60*60*24 => day
...
Edit:
Time period means either minute, hour, day, week, ... as stated above... ?! So all I want is the corresponding time period for a timestamp.
Example: (day = 86400 secs) then a timestamp with getTimeperiod( 85000 ) should be "day".

I think you're searching for something like the class DateInterval ...
It is part of PHP since 5.3.0 and has a static function called createFromDateString() where you can set up a DateInterval from a string like "3600 seconds". From this object you then can get the day, month, year and so on.
Take a look at this page:
http://www.php.net/manual/de/dateinterval.createfromdatestring.php

But is this on the right path returning an interval object (period)? Cred to #SimonSimCity for pointing out DateInterval. If you guide me I could improve the answer.
<?php
$timestamp = 15638400;
echo "The timestamp $timestamp is " . date("Y-m-d H:i:s", 15638400) . "<br \>";
echo "<pre>";
print_r (DateInterval::createFromDateString(date("Y \\y\\e\\a\\r\\s m \\m\\o\\n\\t\\h\\s d \\d\\a\\y\\s\\ H \\h\\o\\u\\r\\s i \\m\\i\\n\\u\\t\\e\\s s \\s\\e\\c\\o\\n\\d\\s", 15638400 ) ) );
echo "</pre>"
?>
Outputting
The timestamp 15638400 is 1970-07-01 00:00:00
DateInterval Object
(
[y] => 1970
[m] => 7
[d] => 1
[h] => 0
[i] => 0
[s] => 0
[invert] => 0
[days] => 0
)

I solved it that way:
/*
seconds 0
minutes 1
hours 2
days 3
week 4
month 5
year 6
decade 7
century 8
millenium 9
*/
$arTimes = array(
0 => 1,
1 => 60,
2 => 60*60,
3 => 60*60*24,
4 => 60*60*24*7,
5 => 60*60*24*7*4,
6 => 60*60*24*7*4*12,
7 => 60*60*24*7*4*12*10,
8 => 60*60*24*7*4*12*10*10,
9 => 60*60*24*7*4*12*10*10*10
);
$nDiff = strtotime( $nTo ) - strtotime( $nFrom );
switch( $nDiff )
{
// check difference and time period
case $nDiff <= $arTimes[ 1 ]:
$nGranularity = 0;
break;
...
}

Related

PHP - Trying to calculate difference between dates get 0 as a result

I am trying to calculate the difference between two dates to get difference in days, months and years but as a result I get 0 on all parameters. I am relatively new to this, for some I am making an obvious mistake, but I cannot understand what I am doing wrong. Would anyone be kind enough to clarify this? I appreciate any answers / help, thanks.
Update
After Markus Zeller's answer I modified my code as follows and it worked. I will make further changes to better suit my needs, but the code as it is works fine. It does not provide the total number of days and months, but these are displayed as age (example 1 year, 3 months and 14 days) and not as (example 1 year 15 months and 471 days). In these two examples the dates were start: 04/15/2021 - end: 07/30/2022
Only problem left
Following the examples above, the correct past days would be 15 (or 471), while I get 14 (or 470). Why is there this 1 day error ?
function difference_between_date() {
$data1 = new DateTime(wp_get_current_user()->user_registered); //Registered User Date
$data2 = new DateTime(); //Current Date
$interval = $data1->diff($data2);
$diffInSeconds = $interval->s; //example 45
$diffInMinutes = $interval->i; //example 15
$diffInHours = $interval->h; //example 6
$diffInDays = $interval->d; //example 20
$diffInMonths = $interval->m; //example 4
$diffInYears = $interval->y; //example 2
echo '<div class="today_date">days' . wp_kses_post($diffInDays) . '</div>';
echo '<div class="today_date">months' . wp_kses_post($diffInMonths) . '</div>';
echo '<div class="today_date">years' . wp_kses_post($diffInYears) . '</div>';
} add_shortcode('diff_date', 'difference_between_date');
PHP has very good DateTime functions. Use them for example:
$date1 = new DateTime('2022-07-30 15:00:00');
$date2 = new DateTime('2020-01-29 14:30:00');
$diff = $date2->diff($date1);
print_r($diff);
gives you all the properties you need. In this example 2 years, 6 months, 1 day and 30 mins or 913 days in total.
DateInterval Object
(
[y] => 2
[m] => 6
[d] => 1
[h] => 0
[i] => 30
[s] => 0
[f] => 0
[weekday] => 0
[weekday_behavior] => 0
[first_last_day_of] => 0
[invert] => 0
[days] => 913
[special_type] => 0
[special_amount] => 0
[have_weekday_relative] => 0
[have_special_relative] => 0
)

how to calculate total PHP dateInterval and show result in date,month,year

I have many PHP DateInterval variables.
example :
//code
$dateInterval1 = startDate1->diff(endDate1);
$dateInterval2 = startDate2->diff(endDate2);
$dateInterval3 = startDate3->diff(endDate3);
//result in dateInterval1, dateInterval2, dateInterval3
$dateInterval1 = DateInterval Object
(
[y] => 1
[m] => 5
[d] => 18
)
$dateInterval2 = DateInterval Object
(
[y] => 2
[m] => 0
[d] => 30
)
$dateInterval3 = DateInterval Object
(
[y] => 0
[m] => 3
[d] => 2
)
I want to find total of dateInterval (dateInterval1+dateInterval2+dateInterval3).
With the specifications as
'startDate1' in begin day. and 'endDate3' in final day isn't continuous.
And Show result in format %d days, %m months %y years As humans understand.
How do I do?
Assuming that your DateInterval objects were created in a similar fashion to below then you can add the constituent parts and re-formulate a new DateInterval with the summed values
$p1=new DateInterval('P1Y5M18D');
$p2=new DateInterval('P2Y0M30D');
$p3=new DateInterval('P0Y3M2D');
$yr=$p1->y + $p2->y + $p3->y;
$mo=$p1->m + $p2->m + $p3->m;
$dy=$p1->d + $p2->d + $p3->d;
$exp=sprintf('P%dY%dM%dD',$yr,$mo,$dy);
$out=new DateInterval( $exp );
echo $out->format('%d days %m months %Y years');
outputs
50 days 8 months 03 years
You need a reference date to have valid numbers for days and months.
$di = [
new DateInterval('P1Y5M18D'),
new DateInterval('P2Y0M30D'),
new DateInterval('P0Y3M2D')
];
$referenceDate = date_create("2000-01-01");
$curDate = clone $referenceDate;
foreach($di as $curDi){
$curDate->add($curDi);
}
$sum = $referenceDate->diff($curDate);
echo $sum->y.' Years and '.$sum->m.' Month and '.$sum->d.' Days';
output:
3 Years and 9 Month and 19 Days
With different reference dates you also have different results because the months have different numbers of days.
With Reference Date 2019-03-01 you get "3 Years and 9 Month and 21 Days" !

How to calculate time difference between SQL time and PHP time

I have set times in SQL in this format: 2016-01-03 12:13:26.
I would like to calculate the number of hours and minutes (if hours<1) going from NOW() to that particular SQL time.
I've been looking at all the different threads here but I can't seem to grasp how to convert PHP different time formats to SQL's.
This is the code I've been using, but this will only give me back hours up to 12, and minutes also. Don't know how to use it with days.
$now = date("d/m/Y h:i:s");
$commentime = strtotime($SQLTIME);
$timetocomment = $now - $commentime;
For instance, this code will yield "12 hours ago" for data I posted 24 hours ago to SQL.
How can I do it? Thank you.
This is my suggestion to use date() in this format date("Y-m-d h:i:s"). Than you will get the complete difference in an array.
function dateDifference($date_1 ,$date_2)
{
$datetime1 = date_create($date_1);
$datetime2 = date_create($date_2);
$interval = date_diff($datetime1, $datetime2);
return $interval;
}
$now = date("Y-m-d h:i:s");
$sqlTime = "2016-01-03 12:13:26";
$DateDiffArr = dateDifference($now,$sqlTime);
echo "<pre>";
print_r($DateDiffArr);
Result Is:
DateInterval Object
(
[y] => 0
[m] => 0
[d] => 0
[h] => 22
[i] => 45
[s] => 55
[weekday] => 0
[weekday_behavior] => 0
[first_last_day_of] => 0
[invert] => 1
[days] => 0
[special_type] => 0
[special_amount] => 0
[have_weekday_relative] => 0
[have_special_relative] => 0
)
In resultant array, you can get the all difference as you need like in years, months, days, minutes, seconds etc.

filtering by date php for this month and last x days and this week

I have a date that returns in a string as 2012-03-19 05:00:32, its not coming from the database
I can use below to search for the last 30 days
$date = '2012-03-19 05:00:32';
if (strtotime($date) >= strtotime('-7 days')) {
// do something
}
Problem is if today is the 19th March, i was to search from the 11th to the 18th for the last 7 days and that seems to search for the last 7 days by calculating 24 hours * 7 by my searches need to start from 00:00:01 each day.
My plan is to break the date down into Year, Month and Day then check if year = 12, then check if month = 3, then check if date between 11 and 18.
Im just wondering if there is a more efficient way to do this or if im on the right track.
I also have the same issue with running a search on all info from this month and also want to search for all info this week starting on Monday.
So this is just asking if my method is sound or if there is a more efficient method.
$mytime = new DateTime('2012-03-19 05:00:32');
$mydate = new DateTime($mytime->format('Y-m-d')); //keep date only, exclude the time component
$now=new DateTime; //includes hours, minutes, seconds
$today=new DateTime($now->format('Y-m-d')); //time set to 0:00
$interval = $mydate->diff($today);
if($interval->format('d') <=7) { //assuming that $mydate isn't in the past
//do something
}
I'd suggest to use DateTime class ...
<?php
$d1=new DateTime("2012-07-08 11:14:15.638276");
$d2=new DateTime("2012-07-08 11:14:15.889342");
$diff=$d2->diff($d1);
print_r( $diff ) ;
/* returns:
DateInterval Object
(
[y] => 0
[m] => 0
[d] => 0
[h] => 0
[i] => 0
[s] => 0
[invert] => 0
[days] => 0
)
*/
?>

Countdown to sunday

I am currently looking at creating a script for my site that will count down to sunday of that week, every week.
Example:
The user visits the site on a saturday at 11:30am, they will be greeted with:
"The next time this page will be updated is in 0 days, 12 hours and 30 minutes."
Any ideas?
You can use this little trick to get a timestamp for midnight next Sunday:
$sunday = strtotime('next Sunday');
See this answer for how to format it into something useful. Right now I get this:
print_r(dateDifference($sunday, time()));
Array
(
[years] => 0
[months_total] => 0
[months] => 0
[days_total] => 0
[days] => 0
[hours_total] => 4
[hours] => 4
[minutes_total] => 256
[minutes] => 16
[seconds_total] => 15387
[seconds] => 27
)
I am using similar to this solution in one of my pojects. You can use it like this:
ago(strtotime("next sunday")) but you need to change $difference = $now - $time; to $difference = $time - $now;
Here's one solution:
http://jsfiddle.net/foxbunny/xBE7L/
It also automatically updates every second.
Edit: I've included the offset parameter, and you use it to supply the difference between user's and server's time-zone if necessary.

Categories