I want to calculate how many weeks there are left from a specific date to another date, in order to get the budget per week. Here's my code:
$date_from = new DateTime('2015-07-28');
$date_to = new DateTime();
$interval = $date_from->diff($date_to);
$daysleft = ($interval->format('%a') + 1);
$weeksleft = number_format($daysleft / 7);
echo ('3164.49' / $weeksleft);
That code prints 3 167,76 for the last 2 weeks which of course is wrong. But what is wrong with my code?
$date_from = new DateTime('2015-07-28');
$date_to = new DateTime();
$interval = $date_from->diff($date_to);
$daysleft = ($interval->format('%a') + 1);
$weeksleft = number_format($daysleft / 7);
echo (floatval('3164.49') / $weeksleft);
Results
1582.245
You can do it in different way as shown below.
$a = strtotime('2015/07/28');
$b = time();
$diff = abs($a - $b);
echo round($diff/(60*60*24*7)); // to get round figure
try this function,
function datediffInWeeks($date1, $date2)
{
if($date1 > $date2) return datediffInWeeks($date2, $date1);
$first = DateTime::createFromFormat('m/d/Y', $date1);
$second = DateTime::createFromFormat('m/d/Y', $date2);
return floor($first->diff($second)->days/7);
}
var_dump(datediffInWeeks('1/2/2013', '6/4/2013'));// 21
I get 1582.245 .. Check/set your timezone settings.
date_default_timezone_set ($timezone_identifier)
http://php.net/manual/en/timezones.php
Related
I need to show the difference between two times in PHP I use strtotime() function to convert my times to integer but my problem is the result not matched what I expected
<?php
$hour1 = '12:00:00';
$hour2 = '9:00:00';
$avg = strtotime($hour1) - strtotime($hour2);
$result = date('h:i:s', $avg); // result = 06:30:00 what I expected is 3:00:00
But the difference is 3:00:00 how to calculate this?
You can create DateTime instances and use diff function to get the difference between 2 times. You can then format them in hours,minutes and seconds.
<?php
$hour1 = '12:00:00';
$hour2 = '09:00:00';
$o1 = new DateTime($hour1);
$o2 = new DateTime($hour2);
$diff = $o1->diff($o2,true); // to make the difference to be always positive.
echo $diff->format('%H:%I:%S');
Demo: https://3v4l.org/X41pv
You can do that:
$hour1 = '12:00:00';
$hour2 = date('h', strtotime('9:00:00'));
$avg= date('h:i:s', strtotime($hour1. ' - '.$hour2.' hours') );
echo $avg; //3:00:00
I have two dates that are in format Y-m-d
$dateOld = new DateTime("2017-01-10");
$dateNew = new DateTime("2017-01-11");
echo $diff = $dateNew->diff($dateOld)->format("%a");
this is working perfect and giving me exact days left.
But now I have added time and it is in H-M format
Like 23:38 and 17:21 and cannot understand now to get the difference between two dateTime
$dateOld = new DateTime("2017-01-10 23:38");
$dateNew = new DateTime("2017-01-11 17:21");
echo $diff = $dateNew->diff($dateOld)->format("%a");
I want to get the difference even if the value if in floating point. Now to work with date concatenated with time?
Use this:
<?php
$dateOld = new DateTime("2017-01-10 23:38");
$dateNew = new DateTime("2017-01-11 17:21");
$diff = $dateNew->diff($dateOld);
$days = $diff->d;
$hours = $diff->h;
$minutes = $diff->i;
$total_difference = $days + ($hours * 60 + $minutes) / 1440;
echo $total_difference;
Or, without the DateInterval:
$dateOld = new DateTime("2017-01-10 23:38");
$dateNew = new DateTime("2017-01-12 17:21");
$difference_in_seconds = $dateNew->getTimestamp() - $dateOld->getTimestamp();
$total_difference_in_days = $difference_in_seconds / 86400;
echo $total_difference_in_days;
Using ->format("%a") will give you the rounded days.
See http://php.net/manual/en/datetime.diff.php.
$dateNew = '2017-01-11 17:21';
$dateOld = '2017-01-10 23:38';
$dateNew = new DateTime($dateNew);
$dateOld = new DateTime($dateOld);
$diff = $dateNew->diff($dateOld);
echo $diff->format("%H:%I");
Source: http://php.net/manual/en/datetime.diff.php
I've been trying to figure out how to output the amount of weeks between 2 dates using strings given to my server.
Every thread I found that has potentially the same problem as me is using datetime() which I'm not extremely familiar with, and I believe uses a different structure than me.
Anyways, I can't figure this out and I've been trying for a couple of hours.
These are the strings I need to feed into the function:
From: "8/3/2015" to: "07/27/2015"
Note, the from string will change each week according to the monday from every week. Also, there are several To dates, and there will be a new one each week.
It would also be a lovely feature if it converted to months and years if it applies.
UPDATE
This is what I came up with, with the help of phplovers answer. This should successfully give you back the amount of days, unless its more than 7, then it would give you weeks, then months, then years.
Pardon the messiness.
$from = date_create($startDate);
$to = date_create($endDate);
$interval = date_diff($from, $to);
if( $interval->format("%a") % 7 == 0 ){
$amt = ($interval->format("%a") / 7);
if($amt == 1) {
$display = $amt . " Week";
} else {
if($amt >= 4) {
$amt2 = $interval->format("%m");
if($amt2 == 1) {
$display = $amt2 . " Month";
} else {
$display = $amt2 . " Months";
$amt3 = $interval->format("%y");
if($amt3 == 1) {
$display = $amt3 . " Year";
} else {
$display = $amt3 . " Years";
}
}
} else {
$display = $amt . " Weeks";
}
}
} else {
$display = ($interval->format("%a")) . " Days";
}
You'd just echo $display anywhere you needed the time difference.
I have used this in some earlier project. Hope this might help you.
function datediffInWeeks($date1, $date2)
{
if($date1 > $date2) return datediffInWeeks($date2, $date1);
$first = DateTime::createFromFormat('d/m/Y', $date1);
$second = DateTime::createFromFormat('d/m/Y', $date2);
return floor($first->diff($second)->days/7);
}
var_dump(datediffInWeeks('8/3/2015', '7/27/2015'));
First thing you need to do is convert the strings to something that is easy to work with. Unixtime is probably the easiest when you are doing comparisons. Unixtime is the number of seconds since the Unix Epoch (January 1, 1970). Here is what I would do:
$date_from = strtotime( '8/3/2015' ) // Change to your input
$date_to = strtotime( '07/27/2015' ) // Change to your input
$difference = $date_to - $date_from; // The seconds between these times
$seconds_in_minute = 60;
$seconds_in_hour = $seconds_in_minute * 60;
$seconds_in_day = $seconds_in_hour * 24;
$seconds_in_week = $seconds_in_day * 7;
$seconds_in_month = $seconds_in_day * 30;
$seconds_in_year = $seconds_in_day * 365;
Each of these variables store how many seconds are in the specific timeframe. What you can do is check agains these variables using some basic math.
$years = floor( $difference / $seconds_in_year );
$months = floor( ($difference - $years * $seconds_in_year ) / ( $seconds_in_month ) );
$days = floor( ( $difference - $years * $seconds_in_year - $months * $seconds_in_month ) / ( $seconds_in_day ) );
This is a long form example of what is happening in the date_diff() function in PHP. However, that function is only available post PHP 5.3, so if you are using an older version of PHP you can try this method.
As MrT stated, using date() functions you can achieve this easily:
$from = date_create("07/27/2015");
$to = date_create("08/03/2015");
$interval = date_diff($from, $to);
echo $interval->format("%a"); // %a will give difference in days
For more about formatting this take a look at date_diff()
Visit: http://php.net/manual/en/datetime.diff.php
$datetime1 = new DateTime('2009-10-11');
$datetime2 = new DateTime('2009-10-13');
$interval = $datetime1->diff($datetime2);
echo $interval->format('%R%a days');
There is an awesome PHP extension for this thing.Its called carbon.
Specifically, for your given task you can do the following(I am skipping the code of importing and stuff):
$dt = Carbon::create(2014, 1, 1);
$dt2 = Carbon::create(2014, 12, 31);
echo $dt->diffInWeeks($dt2);
The above function will give you your answer.
Also, you can use their createFromFormat() method to create carbon objects of date
Link:
http://carbon.nesbot.com/
The 'W' date format fetches the week of the year that the date falls in.
$from = date('W', strtotime('07/27/2015') ) ;
$to = date('W', strtotime('8/3/2015') ) ;
//$from and $to now have the week of the year that their dates fall in.
//This simple math produces the the number of weeks from one date to the next.
$numOfWeeks = $to - $from;
What's the most precise function you have come across to work out an age from the users date of birth. I have the following code and was wondering how it could be improved as it doesn't support all date formats and not sure if it's the most accurate function either (DateTime compliance would be nice).
function getAge($birthday) {
return floor((strtotime(date('d-m-Y')) - strtotime($date))/(60*60*24*365.2421896));
}
$birthday = new DateTime($birthday);
$interval = $birthday->diff(new DateTime);
echo $interval->y;
Should work
Check this
<?php
$c= date('Y');
$y= date('Y',strtotime('1988-12-29'));
echo $c-$y;
?>
Use this code to have full age including years, months and days-
<?php
//full age calulator
$bday = new DateTime('02.08.1991');//dd.mm.yyyy
$today = new DateTime('00:00:00'); // Current date
$diff = $today->diff($bday);
printf('%d years, %d month, %d days', $diff->y, $diff->m, $diff->d);
?>
Try using DateTime for this:
$now = new DateTime();
$birthday = new DateTime('1973-04-18 09:48:00');
echo $now->diff($birthday)->format('%y years'); // 49 years
See it in action
This works:
<?
$date = date_create('1984-10-26');
$interval = $date->diff(new DateTime);
echo $interval->y;
?>
If you tell me in what format your $birthday variable comes I will give you exact solution
WTF?
strtotime(date('d-m-Y'))
So you generate a date string from the current timestamp, then convert the date string back into a timestamp?
BTW, one of the reasons it's not working is that strtotime() assumes numeric dates to be in the format m/d/y (i.e. the US format of date first). Another reason is that the parameter ($birthday) is not used in the formula.
Change the $date to $birthday.
For supper accuracy you need to account for the leap year factor:
function get_age($dob_day,$dob_month,$dob_year){
$year = gmdate('Y');
$month = gmdate('m');
$day = gmdate('d');
//seconds in a day = 86400
$days_in_between = (mktime(0,0,0,$month,$day,$year) - mktime(0,0,0,$dob_month,$dob_day,$dob_year))/86400;
$age_float = $days_in_between / 365.242199; // Account for leap year
$age = (int)($age_float); // Remove decimal places without rounding up once number is + .5
return $age;
}
So use:
echo get_date(31,01,1985);
or whatever...
N.B. To see your EXACT age to the decimal
return $age_float
instead.
This function works fine.
function age($birthday){
list($day,$month,$year) = explode("/",$birthday);
$year_diff = date("Y") - $year;
$month_diff = date("m") - $month;
$day_diff = date("d") - $day;
if ($day_diff < 0 && $month_diff==0){$year_diff--;}
if ($day_diff < 0 && $month_diff < 0){$year_diff--;}
return $year_diff;
}
See BLOG Post
Here is my long/detailed version (you can make it shorter if you want):
$timestamp_birthdate = mktime(9, 0, 0, $birthdate_month, $birthdate_day, $birthdate_year);
$timestamp_now = time();
$difference_seconds = $timestamp_now-$timestamp_birthdate;
$difference_minutes = $difference_seconds/60;
$difference_hours = $difference_minutes/60;
$difference_days = $difference_hours/24;
$difference_years = $difference_days/365;
i hope some help to me ...
i am trouble with some code IN PHP ,maybe you can see function about this :
I need to check is there on Saturday in one period ($date_start ,$date_end )
so :
input : $date_Start (ex: "2010-07-01")
$date_end (ex: "2010-07-12")
output : total saturday : 2 in your range date
but the way thanks before
JOKONARDI
Efficient implementation with no loops for number of Saturdays in the range:
$d1 = new DateTime("2010-07-01"); //including
$d2 = new DateTime("2010-07-12"); //excluding
$diff = $d2->diff($d1);
$days = $diff->format("%a");
$num = floor($days / 7);
$remaining = $days % 7;
$d = $d1->format("w");
if ($d + $remaining > 6)
$num++;
//result in $num