I have this problem. Can someone help me,how to convert number of days into the format XX Years, XX Month, XX Days...
i created this function,
function convert($sum) {
$years = ($sum / 365) ;
$years = floor($years);
$month = ($sum % 365) / 30.5;
$month = floor($month);
$days = ($sum % 365) % 30.5; // the rest of days
// Echo all information set
echo 'DAYS RECEIVE : '.$sum.' days<br>';
echo $years.' years - '.$month.' month - '.$days.' days';
}
convert(151);
But with 151 days the result was wrong
DAYS RECEIVE : 151 days0 years - 4 month - 1 days
it must be 4 month ans 28 days not 1 day...
http://sandbox.onlinephpfunctions.com/code/f5e6b4b4f6a27024b66ffbf04e80698722a3ecab
If you use more modern PHP, the following is based around actual days in each month:
$days = 151;
$start_date = new DateTime();
$end_date = (new $start_date)->add(new DateInterval("P{$days}D") );
$dd = date_diff($start_date,$end_date);
echo $dd->y." years ".$dd->m." months ".$dd->d." days";
Note that it will vary, depending on the current date, so you might prefer to set $start_date and $end_date to work from a fixed baseline
$days = 151;
$start_date = new DateTime('1970-01-01');
$end_date = (new DateTime('1970-01-01'))->add(new DateInterval("P{$days}D") );
$dd = date_diff($start_date,$end_date);
echo $dd->y." years ".$dd->m." months ".$dd->d." days";
This is the solution for your problem:
function convert($sum) {
$years = floor($sum / 365);
$months = floor(($sum - ($years * 365))/30.5);
$days = ($sum - ($years * 365) - ($months * 30.5));
echo “Days received: ” . $sum . “ days <br />”;
echo $years . “ years, “ . $months . “months, “ . $days . “days”;
}
Related
I want to implement Birthday countdown time. Normally, birthday normally takes place once in a year eg within 365 days. I downloaded this code from stackoverflow to check the next birthday day of someone who was born on august 22 1982. the days count down should be less than 365 days but the code below is giving a higher value with negative sign.
$rem = strtotime('1982-22-08') - time();
$day = floor($rem / 86400);
$hr = floor(($rem % 86400) / 3600);
$min = floor(($rem % 3600) / 60);
$sec = ($rem % 60);
if($day) echo "$day Days ";
if($hr) echo "$hr Hours ";
if($min) echo "$min Minutes ";
if($sec) echo "$sec Seconds ";
echo "Remaining...";
the next birthday countdown should be less than 365 days
Thanks
Its because you have wrong date format in strtotime and return nothing.
Documentation says
strtotime — Parse about any English textual datetime description into
a Unix timestamp
So if you use
strtotime('08/22/18')
it will work.
Also you should take actual year if you want say "hey your birthday in this is will be..."
What about trying this method:
$birth_month = 8;
$birth_day = 22;
$year = date('Y');
$month = date('n');
$day = date('j');
if ($birth_month < $month || ($birth_month == $month && $birth_day < $day))
$year++;
$target = mktime(0,0,0,$birth_month,$birth_day,$year);
$today = time();
$rem = abs($target - $today);
$days = (int)($rem/86400);
echo "Remaining days till next birthday: $days days!";
This question already has answers here:
Finding the number of days between two dates
(34 answers)
Closed 3 months ago.
I want to do is to count the days between two dates excluding the weekends and i;m done doing that using the function below. But whenever the $startDate is greater than the $endDate i can't get the proper result. I try to use if ($startDate>$endDate) and i'm stock with that condition and honestly don't know what is the next step.
function getWorkingDays($startDate,$endDate){
// do strtotime calculations just once
$startDate = strtotime($startDate);
$endDate = strtotime($endDate);
//The total number of days between the two dates. We compute the no. of seconds and divide it to 60*60*24
//We add one to inlude both dates in the interval.
$days = ($endDate - $startDate) / 86400 + 0;
$no_full_weeks = floor($days / 7);
$no_remaining_days = fmod($days, 7);
//It will return 1 if it's Monday,.. ,7 for Sunday
$the_first_day_of_week = date("N", $startDate);
$the_last_day_of_week = date("N", $endDate);
// If one of the value is empty it will return "0"
if ($startDate == '' || $endDate == '')
return "0"; // Default value
//---->The two can be equal in leap years when february has 29 days, the equal sign is added here
//In the first case the whole interval is within a week, in the second case the interval falls in two weeks.
if ($the_first_day_of_week <= $the_last_day_of_week) {
if ($the_first_day_of_week <= 6 && 6 <= $the_last_day_of_week) $no_remaining_days--;
if ($the_first_day_of_week <= 7 && 7 <= $the_last_day_of_week) $no_remaining_days--;
}
else {
// (edit by Tokes to fix an edge case where the start day was a Sunday
// and the end day was NOT a Saturday)
// the day of the week for start is later than the day of the week for end
if ($the_first_day_of_week == 7) {
// if the start date is a Sunday, then we definitely subtract 1 day
$no_remaining_days--;
if ($the_last_day_of_week == 6) {
// if the end date is a Saturday, then we subtract another day
$no_remaining_days--;
}
}
else {
// the start date was a Saturday (or earlier), and the end date was (Mon..Fri)
// so we skip an entire weekend and subtract 2 days
$no_remaining_days -= 2;
}
}
//The no. of business days is: (number of weeks between the two dates) * (5 working days) + the remainder
//---->february in none leap years gave a remainder of 0 but still calculated weekends between first and last day, this is one way to fix it
$workingDays = $no_full_weeks * 5;
if ($no_remaining_days > 0 )
{
$workingDays += $no_remaining_days;
}
return $workingDays;
}
$startTimeStamp = strtotime("2011/07/01");
$endTimeStamp = strtotime("2011/07/17");
$timeDiff = abs($endTimeStamp - $startTimeStamp);
$numberDays = $timeDiff/86400; // 86400 seconds in one day
// and you might want to convert to integer
$numberDays = intval($numberDays);
OR
function dateDiff($start, $end) {
$start_ts = strtotime($start);
$end_ts = strtotime($end);
$diff = $end_ts - $start_ts;
return round($diff / 86400);
}
echo dateDiff("2011-02-15", "2012-01-16").'days';
//Get number of days deference between current date and given date.
echo dateDiff("2011-02-15", date('Y-m-d')).'days';
For Count days excluding use below code
$start = new DateTime('7/17/2017');
$end = new DateTime('7/24/2017');
$oneday = new DateInterval("P1D");
$daysName = array('Mon', 'Tue', 'Wed', 'Thu', 'Fri');
$days = array();
foreach(new DatePeriod($start, $oneday, $end->add($oneday)) as $day) {
$day_num = $day->format("N"); /* 'N' number days 1 (mon) to 7 (sun) */
if($day_num < 6) { /* weekday */
$days[$day->format("Y-m-d")] = date('D', strtotime($day->format("Y-m-d")));;
}
}
echo "<pre>";
print_r($days);
echo count($days);
This will check whether start date is less than end date. If yes, then it will display the days.
<?php
if($days = getWorkingDays("2017-05-01","2018-01-01")){
echo $days;
}
function getWorkingDays($startDate,$endDate){
$startDate = strtotime($startDate);
$endDate = strtotime($endDate);
if($startDate <= $endDate){
$datediff = $endDate - $startDate;
return floor($datediff / (60 * 60 * 24));
}
return false;
}
?>
Output: 245
Functions Used:
strtotime(): The strtotime() function parses an English textual datetime into a Unix timestamp
floor(): The floor() function rounds a number DOWN to the nearest integer
Edit-1: Getting Days After Excluding Weekends (saturdays & sundays)
//getWorkingDays(start_date, end_date)
if($days = getWorkingDays("2017-05-01","2018-01-01")){
echo $days;
}
function getWorkingDays($startDate,$endDate){
$days = false;
$startDate = strtotime($startDate);
$endDate = strtotime($endDate);
if($startDate <= $endDate){
$datediff = $endDate - $startDate;
$days = floor($datediff / (60 * 60 * 24)); // Total Nos Of Days
$sundays = intval($days / 7) + (date('N', $startDate) + $days % 7 >= 7); // Total Nos Of Sundays Between Start Date & End Date
$saturdays = intval($days / 7) + (date('N', $startDate) + $days % 6 >= 6); // Total Nos Of Saturdays Between Start Date & End Date
$days = $days - ($sundays + $saturdays); // Total Nos Of Days Excluding Weekends
}
return $days;
}
?>
Sources:
calculate sundays between two dates
The intval() function is used to get the integer value of a variable.
See Description date('N', $date) : N - The ISO-8601 numeric representation of a day (1 for Monday, 7 for Sunday)
There is the script of code for do this.
<?php
$now = time(); // or your date as well
$your_date = strtotime("2010-01-01");
$datediff = $now - $your_date;
echo floor($datediff / (60 * 60 * 24));
?>
or
$datetime1 = new DateTime("2010-06-20");
$datetime2 = new DateTime("2011-06-22");
$difference = $datetime1->diff($datetime2);
echo 'Difference: '.$difference->y.' years, '
.$difference->m.' months, '
.$difference->d.' days';
print_r($difference);
try this
public function datediff($sdate,$edate){
$diffformat='%a';
$date1 = date_create($sdate);
$date2 = date_create($edate);
$diff12 = date_diff($date2, $date1);
$days = $diff12->format($diffformat) + 1;}
EDIT: I noticed in the comment you want to exclude the weekend day/days (however you didn't mention that in your post !)
you can add the number of days you want to exclude from the week
you can use DateTime::diff and use the option for absolute result (positive difference always)
<?php
function daysBetween2Dates($date1, $date2, $execludedDaysFromWeek = 0)
{
try{
$datetime1 = new \DateTime($date1);
$datetime2 = new \DateTime($date2);
}catch (\Exception $e){
return false;
}
$interval = $datetime1->diff($datetime2,true);
$days = $interval->format('%a');
if($execludedDaysFromWeek < 0 || $execludedDaysFromWeek > 7){
$execludedDaysFromWeek = 0 ;
}
return ceil($days * (7-$execludedDaysFromWeek) / 7);
}
Usage Example
// example 1 : without weekend days, start date is the first one
$days = daysBetween2Dates('2016-12-31','2017-12-31');
echo $days;
// example 2 : without weekend days, start date is the second one
$days = daysBetween2Dates('2017-12-31', '2016-12-31');
echo "<br>\n" .$days;
// example 3 : with weekend days, it returns 6 days for the week
$days = daysBetween2Dates('2017-12-31', '2017-12-24',-1);
echo "<br>\n" .$days;
exit;
this outputs
365
365
6
live demo (https://eval.in/835862)
use date_diff() which returns the difference between two DateTime objects.
$diff=date_diff($startDate,$endDate);
I need to get the age of a person. In case of an infant <= 7 days the output should be done in days. If the person is > 2 months and < 1 year the output should be months.
Here I got the problem, that some months are 31 other 30 or 28 days, so my solution isn't exact. Same problem for the else-case: Years with 366 days are ignored by my attempt, so the age isn't calculated correctly.
$timestamp = time();
$birthday_timestamp = mktime(0, 0, 0, $month, $day, $year);
$difference = $timestamp - $birthday_timestamp;
if ($difference < 1209600) return $output = ($difference / 86400)." days";
elseif ($difference < 5184000) return $output = ($difference / 86400 * 7). " weeks";
elseif ($difference < 31536000) return $output = ($difference / 86400 * 30). " months";
else return $output = ($difference / 86400 * 365). " years";
Don't try to calculate dates and differences between dates yourself. PHP has some very nice classes to do that for you.
$now = new DateTime();
$birthDay = new DateTime('1985-05-24');
$diff = $birthDay->diff($now);
var_dump($diff);
This is safe and takes into account leap years and other strange things that will occur when calculating with dates.
$diff will be a DateInterval and contains properties like $y, $m and $d.
I need to extract the total hours in a any month, given just the MONTH and the YEAR, taking into account leap years.
Here is my code so far...
$MonthName = "January";
$Year = "2013";
$TimestampofMonth = strtotime("$MonthName $Year");
$TotalMinutesinMonth = $TimestampofMonth / 60 // to convert to minutes
$TotalHoursinMonth = $TotalMinutesinMonth / 60 // to convert to hours
Just work out the number of days in the month and then multiply by 24, like so:
// Set the date in any format
$date = '01/01/2013';
// another possible format etc...
$date = 'January 1st, 2013';
// Get the number of days in the month
$days = date('t', strtotime($date));
// Write out the days
echo $days;
You can do this:
<?php
$MonthName = "January";
$Year = "2013";
$days = date("t", strtotime("$MonthName 1st, $Year"));
echo $days * 24;
You can use DateTime::createFromFormat since you don't have day
$date = DateTime::createFromFormat("F Y", "January 2013");
printf("%s hr(s)",$date->format("t") * 24);
Well if you are looking at working day its a different approach
$date = "January 2013"; // You only know Month and year
$workHours = 10; // 10hurs a day
$start = DateTime::createFromFormat("F Y d", "$date 1"); // added first
printf("%s hr(s)", $start->format("t") * 24);
// if you are only looking at working days
$end = clone $start;
$end->modify(sprintf("+%d day", $start->format("t") - 1));
$interval = new DateInterval("P1D"); // Interval
var_dump($start, $end);
$hr = 0;
foreach(new DatePeriod($start, $interval, $end) as $day) {
// Exclude sarturday & Sunday
if ($day->format('N') < 6) {
$hr += $workHours; // add working hours
}
}
printf("%s hr(s)", $hr);
<?php
function get_days_in_month($month, $year)
{
return $month == 2 ? ($year % 4 ? 28 : ($year % 100 ? 29 : ($year %400 ? 28 : 29))) : (($month - 1) % 7 % 2 ? 30 : 31);
}
$month = 4;
$year = 2013;
$total_hours = 24 * get_days_in_month($month, $year);
?>
you can use above function to retrieve total days in a month taking into account leap year and then multiply the value to 24
plus, you can also use a cal_days_in_month function but it only supports PHP builds of PHP 4.0.7 and higher.
and if you are using the above "get_day_in_month" then you need to parse the string into integer which can be done like this
FOR MONTH
<?php
$date = date_parse('July');
$month_int = $date['month'];
?>
FOR YEAR
<?php
$year_string = "2013"
$year_int = (int) $year_string
?>
Ok, here is my problem. Instead of measuring 7 days in seconds, I want to count how many weeks (Sunday Through Saturday) there are from date #1 to today.
PHP
$today1 = date("Y-m-d");
$diff = strtotime($date1,0) - strtotime($today1,0);
echo (floor($diff / 604800));
If you're counting in seconds, why use date() when you can use time() instead- it gives out the numeric time signature of your current time, making calculations such as this much easier.
Using seconds is fine, perhaps try something like this:
$date1 = "2012-12-25";
$today1 = time();
$diff = strtotime($date1) - $today1;
if($diff < 604800) {
$week = "this week";
} else {
$week = (floor($diff / 604800) == 1)
? floor($diff / 604800) . " week away" : floor($diff / 604800) . " weeks away";
}
echo $week;