Web Programming TutorialsPHP Date and Time

PHP Date and Time

Today we will learn a most important topic of date and time in this PHP Date and Time tutorial.

Date and time is the most important concept in our day to day life. It has main role in all software projects also. In PHP we can use the date and time wherever required using the functions to get it and set it.

  • We get all the information about current date and time using the function time() in PHP.
  • This time() function returns an integer value that represents the number of seconds elapsed since midnight GMT on 1st January, 1970. This moment is known as the UNIX epoch and the number elapsed since then is known as a timestamp.
  • This timestamp value is difficult to understand, but PHP provides functions to convert this timestamp value into a human understandable and readable format.
  • To demonstrate how the timestamp is obtained create a new folder named date_time in the htdocs folder in xampp folder in C drive. Open a new notepad++ document and save it as index.php in the newly created date_time folder.
  • Write the following code in index.php file:
  • <html>
    <head>
    <title>PHP Date and Time</title>
    </head>
    <body>
    <h1>Timestamp</h1>
    
    <?php
    	print time();
    ?>
    </body>
    </html>
    
  • Here, we have just called a time() function and displayed its output using the print() function.
  • Now open the browser and type localhost/date_time in its address bar and then see the output.
  • The time() function returns the timestamp as shown in the output below:
  • timestamp
    fig 1

  • Many different functions can be used to convert this timestamp value to a human readable date time value.
  • Let us go through some of them.
  1. Converting timestamp using getdate() function:
    • The getdate() function takes a timestamp as a parameter which is optional i.e. necessarily not needed.
    • If any timestamp is not passed to it as a parameter, it works with the current timestamp and returns an associative array that contains the information about date.
    • The table given below has the elements present in the array returned by getdate() function.
    • Key Description Example
      seconds Seconds past the minutes (0-59) 20
      minutes Minutes past the hour (0-59) 29
      hours Hours od the day (0-23) 22
      mday Day of the month (1-31) 11
      wday Day of the week (0-6) 4
      mon Month of the year (1-12) 7
      year Year (4 digits) 1988
      yday Day of year (0-365) 19
      weekday Day of the week Thursday
      month Month of the year January
      0 Timestamp 944584562

      table 1

    • Using these elements it is easy to display date and time in the desired format.
    • Let us go through an example that uses getdate() function and displays all the elements required for date and time.
    • Write the following code in index.php file:
    • <html>
      <head>
      <title>PHP Date and Time</title>
      </head>
      <body>
      <?php
      	//using getdate() function to get the date
      	echo "Use of <strong>getdate</strong> function:<br>";
      	$info=getdate();
      	
      	foreach($info as $key=>$value)
      	{
      		echo $key." = ".$value."<br>";
      	}
      ?>
      </body>
      </html>
      
    • In the above code we have called the getdate() function and assigned the associative array returned by it to the variable $info as shown in the statement below:
    • $info=getdate();
    • All the elements with their values according to the current timestamp are stored in the array assigned to the variable.
    • Because we know that if we don’t provide timestamp as a parameter to getdate() function, it works the current timestamp.
    • The associative array is then displayed using the foreach loop as shown below:
    • foreach($info as $key=>$value)
      {
      		echo $key." = ".$value."<br>";
      }
      
    • Both the key and its value is displayed as shown in the output below:
    • getadate_returned_array_elements
      fig 2

    • Let us now display the date in our desired format.
    • Write the following code in index.php:
    • <html>
      <head>
      <title>PHP Date and Time</title>
      </head>
      <body>
      <?php
      	//using getdate() function to get the date
      	echo "Use of <strong>getdate</strong> function:<br>";
      	$info=getdate();
      	
      	echo "<br><br>Today's date: ".$info["mday"]."/".$info["mon"]."/".$info["year"];
      
      echo "<br><br>Current Time:  ".$info["hours"]." : ".$info["minutes"]." : ".$info["seconds"];
      ?>
      </body>
      </html>
      
    • From table 1 we know that the element mday returns the day, mon returns the month and year returns the year.
    • Using these as the keys in the $info array we retrieve the values and display it concatenating it with the slash(/).
    • Similarly we can display time using hours, minutes and seconds elements.
    • The output is shown below:
    • displaying_date_using_getdate
      fig 3

  2. Converting timestamp using date() function:
    • The date() function is used to return a formatted string representing a date.
    • This date() function accepts 2 parameters: 1) Format and 2) Timestamp.
    • It syntax is given below:
    • date(format,timestamp);
    • The parameter timestamp is optional. If omitted it uses the current date and time to display the date.
    • The parameter format is the format in which the date and time should be displayed.
    • To specify the format of the date and time there are certain codes used for this purpose. Some of them are given in the table below:
    • Format Description Example
      a ‘am’ or ‘pm’ lowercase pm
      A ‘AM’ or ‘PM’ uppercase PM
      d Day of month 20
      m Month of year 1
      y Year ( two digits) 08
      Y Year (4 digits) 2008
      s Seconds of hour 20
      i Minutes (0-59) 23
      H Hour (24-hour-format) 22
      g Hour (12 hour format) 12

      table 2

    • Let us go through an example that uses function date() to display the date and time.
    • Write the following code in index.php file:
    • <html>
      <head>
      <title>PHP Date and Time</title>
      </head>
      <body>
      <?php
      	//using date() function to get the date
      	echo "Use of <strong>date</strong> function:<br>";
      	
      	echo "<br>Date:".date("d/m/Y  G.i:s",time());
      	
      	echo "<br><br>I was in America on ".date("j F Y, \a\\t g.i a",time());
      ?>
      </body>
      </html>
      
    • Here we have used a date function with the format to display the date and time and a current timestamp obtained using time() function.
    • In the date() functions used to display date we used the codes given in table 2 above to specify the format of the date and time.
    • In the first date function we want the date to be printed in the day/month/year format, so we used d/m/Y as the format to specify date. Here we used capital Y because Y gives 4 digit year.
    • Similarly the code G.i:s is used to display the hours, minutes and seconds.
    • In the second date() function we have something like this after date format i.e. \a\\t , this prints at in the string. It is called the escaping the custom characters i.e. we can put our own custom characters using character “\” and then the desired letter.
    • Output of the above output is given below:
    • displaying_date_using_date
      fig 4

  3. Creating a date with mktime() function:
    • We have seen 2 functions used to convert the existing timestamp to human readable date and time.
    • But there are some situations where we have to provide the date.
    • In such situations we can create the date on our own. The function mktime() is used for this purpose.
    • Syntax of mktime() function is given below:
    • mktime(hour,minute,second,month,day,year);
    • Let us see an example: Assume that we are asked for the return date of the book in library, so we need to create the date because it might be certain days ahead.
    • Write the following code in index.php file:
    • <html>
      <head>
      <title>PHP Date and Time</title>
      </head>
      <body>
      <?php
      	//using mktime() function to create date and time
      	echo "Use of <strong>mktime</strong> function:<br><br>";
      	
      	echo "Book issue date: <strong>".date("d-m-Y  h:i:sa")."</strong><br><br>";
      
      	$rd=mktime(17,35,57,10,27,2014);
      
      	echo "The return date of book in library is: <strong>".date("d-m-Y  h:i:sa",$rd)."</strong>";
      ?>
      </body>
      </html>
      
    • In the above code, we have created the date and time using mktime() function and displayed it using date() function.
    • Here, we have displayed the book issue date i.e today’s date and time.
    • Next we want to give the return date of the book which is the eighth day after book issue day.
    • We can create this date using mktime() function. It takes parameters as hour, min, sec, month, day and year.
    • The statement of mktime() function is given below:
    • $rd=mktime(17,35,57,10,27,2014);
    • Here, you can see we have provided value 17 in hour parameter place, because we are using 24 hour time format. I mean after 12 we count 1 as 13, 2 as 14 and so on, hence here we used 17 since we want our time to be set to 5’o clock.
    • All the other parameters are regular.
    • This created date is then displayed using date function as shown in the statement below:
    • echo "The return date of book in library:  <strong>".date("d-m-Y  h:i:sa",$rd)."</strong>";
    • The d-m-Y format is for date (capital Y prints 4 digit year) and h:i:sa format is for time i.e hour:minutes:seconds(am/pm).
    • The output of the above code is given below:
    • creating_date_using_mktime
      fig 5

  4. Some functions used to deal with date and time:
    • There are some functions listed below that can be used to get and set date and time:
    • Function Description Syntax
      checkdate() Validates a Gregorian date. checkdate($month,$day,$year);
      date_dafault_timezone_get() Returns the default timezone. string date_default_timezone_get(void);
      date_dafault_timezone_set() Sets the default timezone. bool date_default_timezone_set(string $timezone_identifier);
      date_parse() Returns associative array with detailed information about given date. array date_parse(string $date);
      date_sun_info() Returns an array with information about sunrise/sunset and twilight begin/end. array date_sun_info(int $time,$float,$latitude,float longitude);
      strtotime() Parses an English textual date or time into a Unix timestamp. int strtotime(string $time [, int $now]);

      table 3

With this we completed learning some things about date and time to use it in PHP projects in this PHP Date and Time tutorial.

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Exclusive content

- Advertisement -

Latest article

21,501FansLike
4,106FollowersFollow
106,000SubscribersSubscribe

More article

- Advertisement -