Showing posts with label PHP Date Functions. Show all posts
Showing posts with label PHP Date Functions. Show all posts

Friday, 2 August 2019

PHP function to get the number of days between two dates

The below function can be used to calculate the difference in days between two dates
USAGE:
/**
 * Getting the number of days between two dates
 * 
 * @param string $date1 yyyy-mm-dd
 * @param string $date2 yyyy-mm-dd
 * @return integer
 */
function getDiffInDays($date1,$date2){
     $datediff = strtotime($date1)-  strtotime($date2);
     return floor($datediff/(60*60*24));
}
$days = getDiffInDays('2013-02-15','2013-01-26');

Calculating the date difference in days using PHP

If you have 2 dates and you need to calculate the total days between these two dates using PHP you will need to do the following
First, we need to convert the two dates into UNIX timestamps in seconds
$date1 = strtotime('2010-10-12');
$date2 = strtotime('2011-11-12');
Calculate the difference between these two dates in seconds
$diff = $date2-$date1;
Get the total of Days
$days = floor($diff/(60*60*24));
The floor function is there to get complete days. 60*60*24 means that each day has 24 hours, each hour has 60 minutes and each minute has 60 seconds.
Complete example
$date1 = strtotime('2010-10-12');
$date2 = strtotime('2011-11-12');
 
$diff = $date2-$date1; 
 
$days = floor($diff/(60*60*24));

Calculating the difference in days between 2 dates in PHP

$startDate = '1999-03-12';
 
$endDate = '2011-03-12';
 
 
$days = (strtotime($endDate)-strtotime($startDate)) / (60 * 60 * 24);
 
echo $days; //Will output 4383
In the above example we have a startdate and a enddate. We need to find out how many days are between the startdate and the enddate.
We convert both dates to a UNIX Timestamp using the strtotime PHP function.
After the conversion we substract the startdate from the endate and then divide it by the number of seconds in a day (60*60*24).
We then output the day difference between 2 dates by using the echo PHP command.

How to transform a month number to the relevant month name using PHP

This can be obtained by combining the date function with the mktime function
For example if I want to get Jan from the number 1 which represents the first monthin the year I would use something similar to the below
$i = 1; //The number 1 represents January
 
echo date("M",mktime(0,0,0,$i,1,2010)); //This will output Jan
So if you want to output Feb the value of $i would be 2 etc
USAGE:
date = string date ( string $format [, int $timestamp ] ) (PHP 4 & 5)
mktime = int mktime ([ int $hour = date(“H”) [, int $minute = date(“i”) [, int $second = date(“s”) [, int $month = date(“n”) [, int $day = date(“j”) [, int $year = date(“Y”) [, int $is_dst = -1 ]]]]]]] )  (PHP 4 & 5)

How to add months to a given date using PHP

By using the PHP functions date and strtotime this can be accomplished.
Example 
$date = '2010-03-22'; 
 
$new_date = date('Y-m-d',strtotime('+4 months',strtotime($date))); 
 
echo $new_date; //Displays 2010-07-22
Explanation of PHP functions:
1)
FUNCTION
date
DESCRIPTION
string
 date ( string $format [, int $timestamp ] )
PARAMETERS USED IN THIS EXAMPLE
Y = A full numeric representation of a year, 4 digits (Examples: 1999 or 2003)
= Numeric representation of a month, with leading zeros (01 through 12)
= Day of the month, 2 digits with leading zeros (01 to 31)
2)
FUNCTION
strtotime
DESCRIPTION
int strtotime ( string $time [, int $now ] )
PARAMETERS
time The string to parse. Before PHP 5.0.0, microseconds weren’t allowed in the time, since PHP 5.0.0 they are allowed but ignored.
now The timestamp which is used as a base for the calculation of relative dates.

How to compare two dates using PHP

  • First we need to convert the two dates to UNIX Timestamps using the PHP function strtotime
  • Then we can compare the two dates in anyway we wish, in the example below I’m checking that the first date is older than the second date 
    $date1 = '1999-10-11';
    $date2 = '2010-10-11';
     
    $firstDate = strtotime($date1);
    $secondDate = strtotime($date2);
     
    if($firstDate < $secondDate){
         echo 'First date is older';
    }else{
         echo 'Second date is older';
    }

How to subtract a number of days from todays date using PHP date function

$var = ‘2007-08-15’;
$var_subtracted_date = date(‘Y-m-d’, strtotime(‘-2 days’, strtotime($var)));
Explanation of PHP functions:
1)
FUNCTION
date
DESCRIPTION
string
 date ( string $format [, int $timestamp ] )
PARAMETERS USED IN THIS EXAMPLE
Y = A full numeric representation of a year, 4 digits (Examples: 1999 or 2003)
= Numeric representation of a month, with leading zeros (01 through 12)
= Day of the month, 2 digits with leading zeros (01 to 31)
2)
FUNCTION
strtotime
DESCRIPTION
int strtotime ( string $time [, int $now ] )
PARAMETERS
time The string to parse. Before PHP 5.0.0, microseconds weren’t allowed in the time, since PHP 5.0.0 they are allowed but ignored.
now The timestamp which is used as a base for the calculation of relative dates.
EXAMPLE
echo strtotime(“now”), “\n”;
echo strtotime(“10 September 2000”), “\n”;
echo strtotime(“+1 day”), “\n”;
echo strtotime(“+1 week”), “\n”;
echo strtotime(“+1 week 2 days 4 hours 2 seconds”), “\n”;
echo strtotime(“next Thursday”), “\n”;
echo strtotime(“last Monday”), “\n”;

Monday, 13 July 2015

PHP: Function to get the last day of a month

<?php
/**
    Last date of a month of a year
    
    @param[in] $month - Integer. Default = Current Month
    @param[in] $year - Integer. Default = Current Year
    
    @return Last date of the month and year in yyyy-mm-dd format
*/
function last_day($month = '', $year = '')
{
   if (empty($month))
   {
      $month = date('m');
   }
   
   if (empty($year))
   {
      $year = date('Y');
   }
   
   $result = strtotime("{$year}-{$month}-01");
   $result = strtotime('-1 second', strtotime('+1 month', $result));

   return date('Y-m-d', $result);
}
?>

Friday, 19 June 2015

PHP: Date function to display all dates between two dates

There is the DatePeriod class.
EXAMPLE:
$begin = new DateTime('2013-02-01');
$end = new DateTime('2013-02-13');

$daterange = new DatePeriod($begin, new DateInterval('P1D'), $end);

foreach($daterange as $date){
    echo $date->format("Y-m-d") . "<br>";
}
(P1D stands for period of one day, see DateInterval for further documentation)
Example:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<style type="text/css">
table,th,td{
    border:1px solid black;
}
th,td{
    height:40px;
    width:140px;
    font-weight:bold;
}
</style>
</head>

<body>
<?php
$start_date = date('Y-m-d',time()-84600);
//echo date('d/m/Y', strtotime('+2 months'));
//echo date('M d Y',$date);
$end_date = date('Y-m-d',strtotime('+3 months'));
//echo date('d/m/Y', strtotime('+1 day'));

//echo strtotime('+1 day');
$begin = new DateTime($start_date);
$end = new DateTime($end_date);

$daterange = new DatePeriod($begin, new DateInterval('P1D'), $end);


?>
<table cellpadding="0" cellspacing="0" width="100%">
    <thead>
        <tr>
                <th>#</th>
                <td>Date</td>
                <td>SM</td>
                <td>Auditing</td>
                <td>Accounts</td>
                <td>IT</td>
        </tr>
    </thead>
    <tbody>
    <?php
    $i=1;
    foreach($daterange as $date){ ?>
        <tr>
            <td rowspan="2"><?php  echo $i; ?></td>
            <td rowspan="2"><?php  echo $date->format("M d Y"); ?></td>
            <td>test</td>
            <td>test</td>
            <td>test</td>
            <td>test</td>
        </tr>
        <tr>
            <td>test</td>
            <td>test</td>
            <td>test</td>
            <td>test</td>
        </tr>
       
        <?php $i++; } ?>
    </tbody>
</table>
</body>
</html>


Another way:
<?php 
  $day = 86400; // Day in seconds  
        $format = 'Y-m-d'; // Output format (see PHP date funciton)  
        $sTime = strtotime($start_date); // Start as time  
        $eTime = strtotime($end_date); // End as time  
        $numDays = round(($eTime - $sTime) / $day) + 1;  
        $days = array();  

        for ($d = 0; $d < $numDays; $d++) {  
            $days[] = date($format, ($sTime + ($d * $day)));  
        }  
 ?>


Friday, 5 June 2015

PHP: Some date and time examples

<?php
$theDate = time();
print date('d-m-y',$theDate);
print ("<br>");
print date('d-m-Y',$theDate);
print ("<br>");
print date('D-M-Y',$theDate);
print ("<br>");
print date('G-i-s',$theDate);
?>

Wednesday, 1 October 2014

Get tomorrows date from date in PHP

<?php

//answer1

$datetime = new DateTime('tomorrow');
echo $datetime->format('Y-m-d H:i:s');


//answer2
$datetime = new DateTime('2013-10-02');
$datetime->modify('+1 day');
echo $datetime->format('Y-m-d H:i:s');


//answer3

$datetime = new DateTime('2013-10-02');
$datetime->add(new DateInterval("P1D"));
echo $datetime->format('Y-m-d H:i:s');


//answer4

echo (new DateTime('2013-10-02'))->add(new DateInterval("P1D"))->format('Y-m-d H:i:s');
                               
$tomorrow_timestamp = strtotime('+1 day', strtotime('2013-10-02'));


echo $tomorrow;



//answer5
//1 Day = 24*60*60 = 86400
echo date("d-m-Y", time()+86400);
?>


<?php

//You could also use the DateTime class. today as 10/01

$date = new DateTime('tomorrow');

echo $date->format('m/d/Y'); # 10/01/2013
//To set the time.

$date->setTime(12, 0 ,0);

echo $date->format('m/d/Y H:i:s'); # 10/02/2013 12:00:00
//In your case.

echo $date->format('l jS F');






echo date('l jS F', strtotime("+1 day"));


$date = date("l jS F", strtotime("tomorrow"));
echo $date;  

?>

Friday, 19 September 2014

PHP - increment date


I want to increment a date , let's say today : $today = date("Y-m-d"), by 3 months during 3 years.
Example : 2014-09-19 -> incremented by 3 months becomes 2014-12-19 -> incremented by 3 months becomes 2015-02-19 and so on until my date it's smaller or equal with 3 years from that date , in our example 2017-09-19.

<?php
 //using DatePeriod
$begin = new DateTime('2014-09-16'); // set the starting date
$end = new DateTime('2017-09-16'); // set the ending date
$interval = new DateInterval('P3M'); // 3 months interval
$range = new DatePeriod($begin, $interval, $end); // set the period
foreach($range as $date) {
    // so foreach three months, this will loop until the end date
    echo $date->format('Y-m-d') . '<br/>'; 
}
 ?>

The output will be:
2014-09-19
2014-12-19
2015-03-19
2015-06-19
2015-09-19
2015-12-19
2016-03-19
2016-06-19
2016-09-19
2016-12-19
2017-03-19
2017-06-19

 <?php
//another way
$today = new DateTime('2014-09-19');
$formatted = $today->modify("+3 months");
echo $formatted->format('Y-m-d');

 ?>
 <?php
//another way
$startDate = date("Y-m-d");
$endDate = date('Y-m-d', strtotime("+3 years", strtotime($startDate )));
echo $startDate."<br/>";
while(strtotime($startDate) < strtotime($endDate) ){
    $startDate = date('Y-m-d', strtotime("+3 months", strtotime($startDate )));
    echo $startDate."<br/>";
} 
 ?>