Reputation: 19822
Say I have the number 234 edit (in days). How can I find how many months ,weeks and days? Is there a function or I have to calculate them myself? My main problem is the months cause they have no fixed number of days (30,31,28).
Actually I am writing an app where the time per charge is entered in days. But in the view I don't want to display "charge per 234 days" but "charge per x months y week n days"
Thanks in advance
Upvotes: 3
Views: 1848
Reputation: 27845
EDIT : Added number of weeks also
<?PHP
$date1 = new DateTime();
$date2 = new DateTime();
$date2->modify('+241 day');
$interval = $date1->diff($date2);
$years = $interval->format('%y');
$months = $interval->format('%m');
$days = $interval->format('%d');
$weeks = (int) ($days / 7);
$days = $days % 7;
echo "$years years $months months $weeks weeks $days days";
?>
EDIT: Doing without DateTime below
refer: How to calculate the difference between two dates using PHP?
$date1 = time();
$date2 = strtotime("+237 day");
$diff = abs($date2 - $date1);
$years = floor($diff / (365*60*60*24));
$months = floor(($diff - $years * 365*60*60*24) / (30*60*60*24));
$days = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24)/ (60*60*24));
$weeks = (int) ($days / 7);
$days = $days % 7;
printf("%d years, %d months,%d weeks, %d days\n", $years, $months, $weeks, $days);
Upvotes: 6
Reputation: 31750
Finding weeks is easy enough, just divide the number of days by 7.
Finding the number of months is a lot more tricky, as the result will depend on the starting date. The number of days in a month differ from month to month, and year to year in the case of February. Without knowing a start date all you could do is approximate by dividing by the average month length (30.4375). If you want to know the actual number of months, you can compute the end date from the known start date and get the number of months difference between them.
The PHP DateTime class should provide the functionality you need to do this.
http://uk.php.net/manual/en/class.datetime.php
Upvotes: 1