Another Date Question

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
JakeJ
Forum Regular
Posts: 675
Joined: Thu Dec 10, 2009 6:27 pm

Another Date Question

Post by JakeJ »

How do I get a date with a girl?

Just kidding!!!

Ok, the real question.

I need to turn $months in to X years and Y months (18 months = "1 Year, 6 months"). This is not a specific date, just some future point in time. I guess it can be based on $months from now. I don't really care that some months have more days than others or that there will be leap years in there, it can be based on a 30 day month.

Thanks!
User avatar
AbraCadaver
DevNet Master
Posts: 2572
Joined: Mon Feb 24, 2003 10:12 am
Location: The Republic of Texas
Contact:

Re: Another Date Question

Post by AbraCadaver »

More of a math question, but:

Code: Select all

$months = 18;
 
$full_years = floor($months / 12);
$remaining_months = ($months % 12);
mysql_function(): WARNING: This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQLextension should be used. See also MySQL: choosing an API guide and related FAQ for more information.
JakeJ
Forum Regular
Posts: 675
Joined: Thu Dec 10, 2009 6:27 pm

Re: Another Date Question

Post by JakeJ »

Here's the solution I came up with even though it's not perfect yet. For some reason the months still always come out plural but I'm fine with it for now. I'll fix it later and post the complete solution.

Code: Select all

function yearsmonths($months) {
$y = floor($months/12);
$m = -(floor($months /12) - $months/12) * 12;
$yearstring = "null";
$monthstring = "null";
 
If ($m == 0) {
    $m = "";
    $monthstring = "";
}
 
If ($m ==1) {
    $monthstring = " month";
}
 
If ($m > 1) {
    $monthstring = " months";
}   
 
If ($y == 0) {
    $y = "";
    $yearstring = "";
 
}
 
If ($y ==1) {
    $yearstring = " year";
}
 
If ($y > 1) {
    $yearstring = " years";
}
 
If ($y != "") {
    If ($m != "") {
        Echo $y, $yearstring,", ", $m, $monthstring;
    }
    Else {
        Echo $y, $yearstring;
    }
}
Else {
    Echo $m, $monthstring;
}
}   
Post Reply