Showing posts with label PHP strtotime. Show all posts
Showing posts with label PHP strtotime. 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 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, 10 September 2018

Using strtotime with PHP

The strtotime() function in PHP allows you to convert English text date time strings into UNIX timestamps. It is useful for converting database datetime strings into UNIX timestamps and also creating dates into the future or past based on the current time or relative to a date and time in the future or the past. This post looks at some examples of doing this.
The PHP function strtotime() has the following usage:
int strtotime ( string $time [, int $now ] )
This means that you pass in a string value for the time, and optionally a value for the current time, which is a UNIX timestamp. The value that is returned is an integer which is a UNIX timestamp.
An example of this usage is as follows, where the date passed to strtotime() might be a date from a database query or similar:
$ts = strtotime('2007-12-21');
This will return into the $ts variable the value 1198148400, which is the UNIX timestamp for the date December 21st 2007. This can be confirmed using the date() function like so:
echo date('Y-m-d', 1198148400);
// echos 2007-12-21
strtotime() is able to parse a wide variety of strings and convert them to the appropriate timestamp, using actual dates and also strings such as "next week", "next tuesday", "last thursday", "2 weeks ago" and so on. Here are some examples:
$ts = strtotime('21 december 2007');
echo $ts, '<br />';
echo date('Y-m-d', $ts), '<br />';
This will display the following:
1198148400
2007-12-21
If today is December 21st, then the following:
$ts = strtotime('next week');
echo $ts, '<br />';
echo date('Y-m-d', $ts), '<br />';

$ts = strtotime('next tuesday');
echo $ts, '<br />';
echo date('Y-m-d', $ts), '<br />';

$ts = strtotime('last thursday');
echo $ts, '<br />';
echo date('Y-m-d', $ts), '<br />';

$ts = strtotime('2 weeks ago');
echo $ts, '<br />';
echo date('Y-m-d', $ts), '<br />';

$ts = strtotime('+ 1 month');
echo $ts, '<br />';
echo date('Y-m-d', $ts), '<br />';
will display the following:
1199006542
2007-12-30
1198494000
2007-12-25
1198062000
2007-12-20
1197192142
2007-12-09
1201080142
2008-01-23

Using strtotime to offset from a different date

If you want to use the PHP function strtotime to add or subtract a number of days, weeks, months or years from a date other than the current time, you can do it by passing the second optional parameter to the strtotime() function, or by adding it into the string which defines the time to parse.
This example shows passing the second parameter. Doing it this way requires that the date to offset from is already a UNIX timestamp. In this example the timestamp being passed is December 25th 2007 (Christmas Day).
$ts = strtotime('tomorrow', 1198494000);
echo $ts, '<br />';
echo date('Y-m-d', $ts);
The result would be:
1198580400
2007-12-26
As you can see, 'tomorrow' has been parsed as tomorrow starting from the 1198494000 timestamp, which is December 25th 2007, resulting in a timestamp being returned as December 26th 2007.
Another way to add or subtract time from an existing time string is to add it into the datetime string like so, where we are adding 90 days on to a date value, in the format of the MySQL date field:
$ts = strtotime('2007-10-12 +90 days');
echo $ts, '<br />';
echo date('Y-m-d', $ts), '<br />';
This would output:
1199876400
2008-01-10
As you can see the strtotime() function is extremely useful for parsing English (and databases) representations of date and time strings and turning them into UNIX timestamps. It is also useful for adding plus and minus offsets to those timestamps to easily create dates and times in the future and past.

Related posts:

Monday, 3 September 2018

PHP string in a date format, add 12 hours

I have this string object in my php array

"2013-03-05 00:00:00+00"
I would like to add 12 hours to the entry within PHP, then save it back to string in the same format
I believe this involves converting the string to a date object. But I'm not sure how smart the date object is and if I need to tell it formatting parameters or if it is supposed to just take the string
$date = new DateTime("2013-03-05 00:00:00+00");
$date->add("+12 hours");
//then convert back to string or just assign it to a variable within the array node

I was getting back empty values from this method or a similar one I tried
How would you solve this issue?
Thanks, your insight is appreciated

Change add() to modify()add() expects a DateInterval object.
<?php
$date = new DateTime("2013-03-05 00:00:00+00");
$date->modify("+12 hours");
echo $date->format("Y-m-d H:i:sO");

Here's an example using a DateInterval object:
<?php
$date = new DateTime("2013-03-05 00:00:00+00");
$date->add(new DateInterval('PT12H'));
echo $date->format("Y-m-d H:i:sO");

Friday, 31 August 2018

PHP strtotime () does not produce anything

Here is my PHP code:

echo '<br />1. '.$w_time_no;
echo '<br />2. '.strtotime($w_time_no);
echo '<br />3. '.date('G:i', strtotime($w_time_no));

That's what I get:
1. 0000-00-00 22:00:00
2.
3. 2:00

Why strtotime() outputs nothing by itself? Is there something wrong with server settings? Server: Apache/2.2.11 (Win32), PHP 5.2.10, MySQL client version: 5.0.51a.

strtotime doesn't "output" anything, btw : it returns false in case of an error ; see the manual :
Return Values
Returns a timestamp on success, FALSE otherwise. Previous to PHP 5.1.0, this function would return -1 on failure.
What doesn't output anything is echo : false is considered as an empty string, and nothing get outputed.
strtotime's documentation also gives the valid range for dates :
Note: The valid range of a timestamp is typically from Fri, 13 Dec 1901 20:45:54 UTC to Tue, 19 Jan 2038 03:14:07 UTC. (These are the dates that correspond to the minimum and maximum values for a 32-bit signed integer.) Additionally, not all platforms support negative timestamps, therefore your date range may be limited to no earlier than the Unix epoch. This means that e.g. dates prior to Jan 1, 1970 will not work on Windows, some Linux distributions, and a few other operating systems. PHP 5.1.0 and newer versions overcome this limitation though.
'0000-00-00' is outside of this range, so it's not considered a valid date ; hence the false return value.
As a sidenote, to really know what's inside a variable, you can use var_dump.
As a bnus, used with Xdebug, it'll get you a nice-formated output ;-)

Thursday, 30 August 2018

PHP sort array with date as key with date format


This question already has an answer here:


  • How to sort a date array in PHP 4 answers
I have an array as follow: The first key element is a date with the format dd-mm-yyyy
Array
(
    [08-12-2015] => Array
        (
          ------------
        )
    [07-12-2015] => Array
        (
          ------------
        )
    [09-12-2015] => Array
        (
          ------------
        )
)

Is it possible to sort this array on the first key value bij date? So the first element is
Array
(
    [07-12-2015] => Array
        (
          ------------
        )
    [08-12-2015] => Array
        (
          ------------
        )
    [09-12-2015] => Array
        (
          ------------
        )
)


Yes, I found the solution:
function order_date($a1,$b1) {
    $format = 'd-m-Y';
    $a = strtotime(date_format(DateTime::createFromFormat($format, $a1), 'Y-m-d H:i:s'));
    $b = strtotime(date_format(DateTime::createFromFormat($format, $b1), 'Y-m-d H:i:s'));
    if ($a == $b)
    {
        return 0;
    }
    else if ($a > $b)
    {
        return 1;
    }
    else {
        return -1;
    }
}

uksort($array, "order_date");

Monday, 20 July 2015

PHP: Expiry date code

<?php
    date_default_timezone_set ("Asia/Calcutta");
    $dateofreg1=date("M d Y");
    $puechese_date="08/13/2014";
    $startTime = strtotime($puechese_date);
    $endTime = strtotime($dateofreg1);
    $timeDiff = abs($startTime-$endTime);
    $numberDays = $timeDiff/86400;
    $numberDays = intval($numberDays);
    $validays="90";
    if($numberDays>$validays)
        {
        echo "Product Valid";
        }
    else
        {
        echo "Product Expired";
        }
?>

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);
}
?>

Saturday, 27 June 2015

Mysql: How convert mysql date in php, back and foward

Dates in PHP and MySQL

I see a lot of people on forums and on my training courses asking about the
best way (or any way) to manage dates stored in a MySQL database and used in PHP.
Three options follow, but first the problem. PHP uses unix timestamps for all its date functionality.
It has methods to convert these timestamps into pretty much any text format you
could want but internally it uses the timestamp format. A timestamp is simply an integer.
Specifically, it's the number of seconds that have elapsed since
midnight on January 1st 1970 (greenwich mean time).
MySQL has three date types for use in columns. These are DATETIME, DATE, and TIMESTAMP.
DATETIME columns store date and time in some internal format (I've not found what that is)
for efficiency but always converts them to/from a string in the form YYYY-MM-DD HH:MM:SS
(e.g. 2006-12-25 13:43:15) when accessing them. DATE columns use just the date part of
this format - YYYY-MM-DD (e.g. 2006-12-25). TIMESTAMP columns, despite their name, are
nothing like the unix timestamps used in PHP. A TIMESTAMP column is simply a DATETIME column
that automatically updates to the current time every time the contents of that record are
altered. (That's a simplification but broadly true and the details are not important here).
In particular, since version 4.1 of MySQL the TIMESTAMP format is exactly the same as the
DATETIME format.

So the problem is how to work with these two very different date formats -
the PHP timestamp integer and the MySQL DATETIME string. There are three common
solutions...
  1. One common solution is to store the dates in DATETIME fields and use PHPs date() and strtotime() functions to convert between PHP timestamps and MySQL DATETIMEs. The methods would be used as follows -
    $mysqldate = date( 'Y-m-d H:i:s', $phpdate ); $phpdate = strtotime( $mysqldate );
  2. Our second option is to let MySQL do the work. MySQL has functions we can use to convert the data at the point where we access the database. UNIX_TIMESTAMP will convert from DATETIME to PHP timestamp and FROM_UNIXTIME will convert from PHP timestamp to DATETIME. The methods are used within the SQL query. So we insert and update dates using queries like this -
    $query = "UPDATE table SET
        datetimefield = FROM_UNIXTIME($phpdate)
        WHERE...";
    $query = "SELECT UNIX_TIMESTAMP(datetimefield)
        FROM table WHERE...";
  3. Our last option is simply to use the PHP timestamp format everywhere. Since a PHP timestamp is a signed integer, use an integer field in MySQL to store the timestamp in. This way there's no conversion and we can just move PHP timestamps into and out of the database without any issues at all.
    Be aware, however, that by using an integer field to store your dates you lose a lot of functionality within MySQL because MySQL doesn't know that your dates are dates. You can still sort records on your date fields since php timestamps increase regularly over time, but if you want to use any of MySQL's date and time functions on the data then you'll need to use FROM_UNIXTIME to get a MySQL DATETIME for the function to work on.
    However, if you're just using the database to store the date information and any manipulation of it will take place in PHP then there's no problems.

So finally we come to the choice of which to use. For me, if you don't need to manipulate the dates within MySQL then there's no contest and the last option is the best. It's simple to use and is the most efficient in terms of storage space in the data table and speed of execution when reading and writing the data.

However, some queries will be more complicated because your date is not in a date field (e.g. select all users who's birthday is today) and you may lose out in the long run. If this is the case it may be better to use either option 1 or 2. Which of these you use depends on whether you'd rather place the work on MySQL or PHP. I tend to use option 2 but there's no right or wrong answer - take your pick.

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)));  
        }  
 ?>


Tuesday, 2 June 2015

PHP: Date range overlap check

<?php // Function to test for time overlap 
// $start_time    A start date YYYY-MM-DD HH:MM:SS 
// $end_time      An end date YYYY-MM-DD HH:MM:SS 
// $times         An array of times to match against 
// Returns true if there is an overlap false if no overlap is found 
function time_overlap($start_time$end_time$times){ 
    
$ustart strtotime($start_time); 
    
$uend   strtotime($end_time); 
    foreach(
$times as $time){ 
        
$start strtotime($time["start"]); 
        
$end   strtotime($time["end"]); 
        if(
$ustart <= $end && $uend >= $start){ 
            return 
true; 
        } 
    } 
    return 
false; 
} 
// A test list of times $list_of_times = array( 
    array( 
        
"start" => "2012-01-01 00:00:00", 
        
"end" => "2012-01-30 00:00:00" 
    
), 
    array( 
        
"start" => "2012-02-01 00:00:00", 
        
"end" => "2012-02-30 00:00:00" 
    
), 
    array( 
        
"start" => "2012-03-01 00:00:00", 
        
"end" => "2012-03-30 00:00:00" 
    
) 
); 
// Test some times if(!time_overlap("2012-03-15 00:00:00""2012-04-01 00:00:00"$list_of_times)){ 
    echo 
"No overlap found adding to array!<br />"; 
    
$list_of_times[]["start"] = "2012-03-15 00:00:00"; 
    
$list_of_times[]["end"] = "2012-04-01 00:00:00"; 
}else{ 
    echo 
"Overlap found time not added to array!<br />"; 
} 

if(!
time_overlap("2012-04-15 00:00:00""2012-05-01 00:00:00"$list_of_times)){ 
    echo 
"No overlap found adding to array!<br />"; 
    
$list_of_times[]["start"] = "2012-03-15 00:00:00"; 
    
$list_of_times[]["end"] = "2012-04-01 00:00:00"; 
}else{ 
    echo 
"Overlap found time not added to array!<br />"; 
}