PHP

Calculating the Difference Between Two Dates

$century = mktime(12, 0, 0, 1, 1, 2001);
$today = time();
$difference = $today - $century;

The epoche value that can be determined by time() and other PHP functions can be used to easily calculate the difference between two dates. The trick is to convert the dates into time stamps (if not already available in this format). Then the difference between these two time stamps is calculated. The result is the time difference in seconds. This value can then be used to find out how many minutes, hours, and days this corresponds to:

  • Divide the result by 60 to get the number of minutes

  • Divide the result by 60 * 60 = 3600 to get the number of hours

  • Divide the result by 60 * 60 * 24 = 86400 to get the number of days

The Difference Between Two Dates
<?php
  $century = mktime(12, 0, 0, 1, 1, 2001);
  $today = time();
  $difference = $today - $century;
  echo 'This century started ';
  echo floor($difference / 84600);
  $difference -= 84600 * floor($difference / 84600);
  echo ' days, ';
  echo floor($difference / 3600);
  $difference -= 3600 * floor($difference / 3600);
  echo ' hours, ';
  echo floor($difference / 60);
  $difference -= 60 * floor($difference / 60);
  echo " minutes, and $difference seconds ago.";
?>

If you start with the number of days, round down each result and substract this from the result; you can also split up the difference into days, hours, and minutes.

Using GMT Date/Time Information

Usually, PHP takes the local settings for time formats. However in some special cases, the GMT time format must be used. For this, PHP offers "GMT-enabled" versions of some of its date/time functions:

  • gmdate() works like date() and formats a date/time value; however, the return value uses GMT format

  • gmmktime() creates a time stamp like mktime(); however, it uses GMT

  • gmstrftime() formats a time as strftime() does; however, it uses GMT

GMT is important when it comes to setting a page's expiry date in an HTTP header or manually setting the expiry date of a cookie, also in the HTTP header.

What Does PEAR Offer?

The following PEAR packages offer functionality helpful for processing form data of any kind:

  • Date contains a set of functions to work with various date/time values, including conversions between time zones and various date/time representations

  • Date_Holidays calculates the names and dates of special holidays

by BrainBellupdated
Advertisement: