Jump to content

Converting a long string of days into (Year, Month, Days) format


envexlabs

Recommended Posts

Hey,

 

I have a function that converts 2 dates into a string of days inbetween those two dates.

 

So if the string is returned as 124512 days, how would i go about figuring out how many years/months/days that is?

 

Any ideas of where to even start?

 

Thanks,

 

envex

Link to comment
Share on other sites

UPDATE

 

I think i've figured it out, any critique on my code? Tear it apart please!

 

function days_between($day){

$daysin = array(31,28,31,30,31,30,31,31,30,31,30,31);

$years = $day / 365;
$years = floor($years);

$removedays = $years * 365;
$days = $day - $removedays;

if($days <= 31){
	$days = $days;
	$months = 0;
}else{

	for($i = 1; $i <= 12; $i++){

		if($days >= 0){

			$days = $days - $daysin[$i];
			$months = $months + 1;

		}

	}

	$days = $days + $daysin[$months];	
}

$days = $days != 0 ? "$days days" : '';
$months = $months != 0 ? "$months months, " : '';
$years = $years != 0 ? "$years years, " : '';

$time =  $years.$months.$days;

return $time;

}

Link to comment
Share on other sites

couple errors

<?php function days_between($day){

$daysin = array(31,28,31,30,31,30,31,31,30,31,30,31);

$years = $day / 365;
$years = floor($years);

$removedays = $years * 365;
$days = $day - $removedays;

if($days <= 31){
	$days = $days;
	$months = 0;
}else{

	for($i = 1; $i <= 12; $i++){

		if($days >= $daysin[$i]){ //make sure its more than current month so you dont get negative days

			$days = $days - $daysin[$i];
			$months = $months + 1;

		}
else break;

	}

	//$days = $days + $daysin[$months];	
}

$days = $days != 0 ? "$days days" : '';
$months = $months != 0 ? "$months months, " : '';
$years = $years != 0 ? "$years years, " : '';

$time =  $years.$months.$days;

return $time;

}?>

 

think that looks better.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.