Use date and time Functions in PHP


In developing a web-based application, processing date is often required. For example, recording the date of the transaction, record the date and time of the last time a user logged in, also the date settings on publishing an article or website content. On this occasion I will share about the basics of using date and time functions in PHP. In the real case, using date and time function customized on the conditions and needs, as well as the format of the date that results from a function. PHP as a web programming language that is very popular among webmasters has been providing functions to manipulate date and time are quite complex.

Syntax :
string date(string $format,int $timestamp);
Explanation:
Date function will return the date format in the form of a string based on the given value in the parameter  $format. Timestamp parameter is optional, the granting of this parameter value is adjusted at its use, by default $timestamp value is the result of the function time().

Example:
$current_date=date('m/d/Y');
The use of the function date() above will result the date on the server when the script is executed, the output format is month/day/Year. I assume the script is running on January 10, 2015, then the output of the function is the 01/10/2015. In certain circumstances, we need to get a date but not a current date, we assume we need to get the date three days later and five days in advance.

Code snippet to get the date three days later:
$three_days_later=date('F d, Y',time() + 60*60*24*3);
echo "Three days later : ".$three_days_later;

In the above script uses the function time(), time() function is used to get the value of the seconds counted from the date of January 1, 1970 00:00:00. The value of the time() function is then added to the result of 60 *60*24* 3 or the tick value in three days which was converted using the date function with 'F d, Y' format.

Code snippet to get date five days ago:
$five_days_ago=date('F d, Y',time() - 60*60*24*5);
echo "Five days ago : ".$five_days_ago;
in the script above the value of the time() function is reduced by the tick value of five-day then converted by date function with 'F d, Y' format.
In order to know more about the formats that can be used on the date function in General, you can refer to the table below.

date Function Formats:

FORMAT
DESCRIPTION
a
This format is used to provide a description of am/pm
d
Used to retrieve the value of the day with a two-character numeric format
D
Gets the name of the day with a three-letter format.
F
Get the full month name, e.g. 'January'
h
Take hours with two characters 12 hour formats
H
Take hours with two characters 24 hour formats
i
get the minutes value with the two characters formats '00-59'
l (L Lowercase)
Get the full name of the day, e.g. ‘Saturday’
j
get the day with ‘1-31’ format
m
get the month value with two characters format ’01-12’
M
get the name of the month with three-letter format, e.g. ‘Jan’
s
Gets the value of the seconds with the two characters formats '00-59'
t
get the number of days in a month
w
Determine the position of the day on a week with the format ' 0-6 = Sunday-Saturday '
y
Get the year with the two characters numeric format
Y
Get the year with four characters numeric format
z
Get the number of days in a year.

Calculate the difference between two dates 
<?
$first_date="01/10/2015";
$second_date="01/15/2015";
$first_date_part=explode("/",$first_date);
$second_date_part=explode("/",$second_date);
$conversion_first_date=mktime(0,0,0,$first_date_part[0],$first_date_part[1],$first_date_part[2]);
$conversion_second_date=mktime(0,0,0,$second_date_part[0],$second_date_part[1],$second_date_part[2]);
echo "First Date : ".date('F d, Y',$conversion_first_date)."<br/>";
echo "Second Date : ".date('F d, Y',$conversion_second_date)."<br/>";
$difference=$conversion_second_date-$conversion_first_date;
$difference_in_day=$difference/(60*60*24);
echo "The difference of both date are : ".$difference_in_day." Days";
?>
The following explanation of the script above:

$first_date="01/10/2015";
$second_date="01/15/2015";
Specify the value $first _date and $second _ date where both variables are filled in the date format 'm/d/Y '.

$first_date_part=explode("/",$first_date);
$second_date_part=explode("/",$second_date);
Split the string on the variables $first and $second using the explode() function with the string '/' as sparator, so the variables $first_date_part and $second_date_part would be worth array(0=>'string month',1=>'string day',2=>'string year').

$conversion_first_date=mktime(0,0,0,$first_date_part[0],$first_date_part[1],$first_date_part[2]); $conversion_second_date=mktime(0,0,0,$second_date_part[0],$second_date_part[1],$second_date_part[2]);
Previously will be explained in advance of mktime() function. mktime() function in PHP will return the value of a timestamp according to the parameters that are accepted by the function. The syntax of the mktime() function is as follows: mktime(hour,minute,second,month,day,year);

The use of mktime() function on the above script will giving timestamp value in the $conversion_first_date and $conversion_second_date variables.

After getting the timestamp from both these dates, then calculated the difference between the both dates that result then accommodated in the $difference variable. Because of the difference that will be displayed in days value, then the $difference variable, which is worth of seconds will be converted into days value with this script  '$difference_in_day = $difference/(60 * 60 * 24);' which the result is accommodated in the $difference _ in_day variable.

Validate the two dates from HTML Form
Often a web application allowing users to give input as date to the server, this time it will be discussed how do filters whether the received date by the server according to the format required by the application. Note the script below:

Create an html form as the interface to the user for entries such as the following
<html>
 <head>
   <title>Check Date From User Input</title>
 </head>
 <body>
 <form method="post" action="<?=$_SERVER['PHP_SELF']?>">
   <p>First Date : <input type="text" name="date1"> Format date 'm/d/Y' example 01/10/2015
   </p>
   <p>Second Date : <input type="text" name="date2"> Format date 'm/d/Y' example 01/10/2015   </p>
   <input type="submit" value="Submit" name="submit">
 </form>
 </body>
</html>
Then put the following script below appropriately under the tag <body> to proccess the input dates from user.
<?
if(isset($_POST['submit'])){
  $date1=$_POST['date1'];
  $date2=$_POST['date2'];
  $message="";
  if(!preg_match('/^[0-9]{2}+[\/-]{1}+[0-9]{2}+[\/-]{1}+[0-9]{4}+$/',$date1)){
     $message="<li>Please fill the First Date with the valid date format 'd/m/Y'</li>";
  }
  else{
    if(!checkdate(substr($date1,0,2),substr($date1,3,2),substr($date1,6,4))){
      $message="<li>Please fill the First Date with the valid date format 'd/m/Y'</li>";
    }
  }
  if(!preg_match('/^[0-9]{2}+[\/-]{1}+[0-9]{2}+[\/-]{1}+[0-9]{4}+$/',$date2)){
     $message="<li>Please fill the Second Date with the valid date format 'd/m/Y'</li>";
  }
  else{
    if(!checkdate(substr($date2,0,2),substr($date2,3,2),substr($date2,6,4))){
      $message="<li>Please fill the Second Date with the valid date format 'd/m/Y'</li>";
    }
  }
  if(empty($message)){
    $first_date_part=explode("/",$date1);
    $second_date_part=explode("/",$date2);      $conversion_first_date=mktime(0,0,0,$first_date_part[0],$first_date_part[1],$first_date_part[2]);
$conversion_second_date=mktime(0,0,0,$second_date_part[0],$second_date_part[1],$second_date_part[2]);
    echo "First Date : ".date('F d, Y',$conversion_first_date)."<br/>";
    echo "Second Date : ".date('F d, Y',$conversion_second_date)."<br/>";
    $difference=$conversion_second_date-$conversion_first_date;
    $difference_in_day=$difference/(60*60*24);
    echo "The difference of both date are : ".$difference_in_day." Days";
  }
  else{
    echo "<ul>".$message."</ul>";
  }
}
?>
To validate the input date from the user, the first thing to note is the date pattern is already in compliance with required by the system. To examine patterns of dates, we can use the preg_match() function. To use preg_match() you can see the following code in the script above:
preg_match('/^[0-9]{2}+[\/-]{1}+[0-9]{2}+[\/-]{1}+[0-9]{4}+$/',$date1)
The code to check if the date format that is sent by the user formatted 'm/d/Y ' or (month{2}/day{2}/year{4}). In the previous article has been discussed about using preg_match to validate input text from an html form. After examining the pattern of dates, next is checking the value of month, day and year with checkdate() function. The syntax of checkdate function is Boolean checkdate (string $month,string $day, string $year);
In the script above usage checkdate() function is on the following code:
if(!checkdate(substr($date1,0,2),substr($date1,3,2),substr($date1,6,4))){
  //statement
The $month parameter in the code is filled with the value of $date1 variable start from zero index by as much as two characters, $day parameter filled by value of $date1 variable start from the third index with length two character and the $year parameter is filled by the value of $date1 variable start the index from sixth with length four character. If the checkdate function return the true value it's meaning that the date that send by user is okay, you can adding the code to process the date after that selection or in the line that marked as //statement, change the line with your code. So, hopefully this article can help. Thank's for your attention.

Download Code Samples