Date handling on PHP

Date handling on PHP

Current time and date

UNIX machines work with time in the following way. They count seconds since the night of 1 January 1970. It is called UNIX era. So, if we had PHP code similar to:

<?php
echo time();
?>

it will return the following result:


958905820


It’s just the same as 12:43 PM Sunday 21 May 2000.

A lot of functions that handle date in PHP require time that is returned by function time(). As the ways of using time in UNIX and Windows are the same it allows using code on different platforms without any problems. Here is one more advantage. As time () function returns the whole number it can be stored in the database as well as in the text file. There is no use in date and time storing in the single cells of the database.

Displayed date type changing. Date and time formatting.

PHP has two ways of changing UNIX time. First way is a function date(). That function has two arguments. First argument is a line that defines the formatting that should be returned, second argument is UNIX time. Formatting line is a set of special symbols that show parts of time and date you chose. For example, we need to show the following date: "18h01 Sunday 21 May".

We’ll use one of the special symbols for every changeable bit in the line. There are several symbols that will return such data as day, month and year. For our example we need the following symbols:

  • 'H' – returns hour
  • 'i' – returns minutes
  • 'I' – returns weekday
  • 'd' – returns monthday
  • 'F' – the full name of the month

Our line will have the following form: “Hhi l d F”. PHP script will have the following script:

<?php
echo date("Hhi l d F"time());
?>

If we launch that code we’ll get:

180609 Sunday 21 May

It can look strange because h in lower case means time in the 12-hour format. Here we have two ways out. First is that we can escape h in lower case and write:

<?php
echo date("H\hi l d F"time());
?> 

The result is 18h12 Sunday 21 May

There is one more function - getdate(). That function requires only the UNIX time in the form of the argument and it returns associative array of the elements in the date.

For example:

<?php
$date_time_array 
getdate(time());
echo 
$date_time_array["weekday"];
?>

It will return:

Sunday

Other parts of the array are:

  • "seconds" - seconds
  • "minutes" - minutes
  • "hours" - hours
  • "mday" – monthday
  • "wday" – weekday in the numeral format
  • "mon" – month in the numeral format
  • "year" - year
  • "dyear" – day of the year in the numeral format
  • "month" – full name of the month

Date transformation to the UNIX time

Sometimes there can appear necessity of working with data in some date and time format. Date can be set in the format YYYY/MM/DD. It means that current date input will have the following view: 2000/05/27. Function mktime() can take the value of different parts of the date and transform them to the UNIX time./p>

Function format is as follows:

int mktime(int hour, int minute, 
int second, int month, int day, int year, int [is_dst] ); 

Script will have the following form:

<?php
echo mktime(0,0,0,5,27,2000);
?> 

I put nulls instead of hours, minutes and seconds. Thus we got a midnight.

<?php

$access_date 
"2000/05/27";

// function explode() splits the line 
$date_elements  explode("/",$access_date);

// here
// $date_elements[0] = 2000
// $date_elements[1] = 5
// $date_elements[2] = 27

echo mktime(0,0,0,$date_elements[1],
$date_elements[2],$date_elements[0]);
?> 

Let’s complicate our task and imagine that we have to get date and time in the following format:

2000/05/27 02:40:21 PM

<?php

// line got from the Access
$date_time_string "2000/05/27 02:40:21 PM";

// Spliting the line into three parts - date, time and AM/PM 
$dt_elements explode(" ",$date_time_string);

// Date splitting 
$date_elements explode("/",$dt_elements[0]);

// Time splitting
$time_elements =  explode(":",$dt_elements[1]);

if (
$dt_elements[2] == "PM") {
    
$time_elements[0] += 12;
}

// result output
echo mktime($time_elements[0], $time_elements[1],$time_elements[2], 
$date_elements[1],$date_elements[2], $date_elements[0]);

?> 

Date changing

There are a lot of cases when you need to know time in 6 hours, day that was 35 days ago etc. We know how function mktime() can be used for UNIX time generation. What should we do if we need to get UNIX time from the current date and time? mktime() function has the following arguments: hour , minute, second , month, day , year. Function getdate() can give us all that part and bits.

<?php
// Gets the current time to the array 
$timestamp time();
echo 
$timestamp;
echo 
"<p>";
$date_time_array getdate($timestamp);

// use mktime for updating UNIX time
$timestamp mktime(
    
$date_time_array["hours"],
    
$date_time_array["minutes"],
    
$date_time_array["seconds"],
    
$date_time_array["mon"],
    
$date_time_array["mday"],
    
$date_time_array["year"]
    );
echo 
$timestamp;
?> 

We’ll add several variables and everything will be clear:

<?php

// Gets the current time to the array
  
$timestamp time();
echo 
$timestamp;
echo 
"<p>";
$date_time_array getdate($timestamp);

$hours $date_time_array["hours"];
$minutes $date_time_array["minutes"];
$seconds $date_time_array["seconds"];
$month $date_time_array["mon"];
$day $date_time_array["mday"];
$year $date_time_array["year"];

// use mktime for updating UNIX time
$timestamp mktime($hours,$minutes,$seconds,$month,$day,$year);
echo 
$timestamp;
?> 

When we got information from the array that was created by getdate() function our code became more simple. Now, if you need to add 19 hours to the current time you can write $hours +19. mktime() function will switch to the next day.

<?php

// Gets the current time to the array
$timestamp time();
echo 
strftime("%Hh%M %A %d %b",$timestamp);
echo 
"<p>";
$date_time_array getdate($timestamp);

$hours $date_time_array["hours"];
$minutes $date_time_array["minutes"];
$seconds $date_time_array["seconds"];
$month $date_time_array["mon"];
$day $date_time_array["mday"];
$year $date_time_array["year"];

// use mktime for updating UNIX time
// adding 19 hours to $hours
$timestamp mktime($hours 19,$minutes,$seconds,$month,$day,$year);
echo 
strftime("%Hh%M %A %d %b",$timestamp);
echo 
"&lt;br&gt;~E after adding 19 hours";

?> 

Working of that script will show:

14h58 Saturday 03 Jun 
09h58 Sunday 04 Jun
~E after adding 19 hours 

Time subtraction works analogously.

DateAdd function creating on PHP

The reason of writing that article is that I couldn’t find function in PHP that is similar to DateDiff in ASP. We have explained the process of working with date and time in PHP, and now we’ll try to import two functions that are used in ASP. First function is DateAdd.

Intervals can be as follows:

yyyy year
q quarter
q quarter
m month
y day of the year
d day
w weekday
ww week
h hour
n minute
s second

Here w, y and d add one day to the current day, q adss three month, ww adds 7 days.

<?php

function DateAdd($interval$number$date) {

    
$date_time_array getdate($date);
    
$hours $date_time_array["hours"];
    
$minutes $date_time_array["minutes"];
    
$seconds $date_time_array["seconds"];
    
$month $date_time_array["mon"];
    
$day $date_time_array["mday"];
    
$year $date_time_array["year"];

    switch (
$interval) {
    
        case 
"yyyy":
            
$year+=$number;
            break;
        case 
"q":
            
$year+=($number*3);
            break;
        case 
"m":
            
$month+=$number;
            break;
        case 
"y":
        case 
"d":
        case 
"w":
            
$day+=$number;
            break;
        case 
"ww":
            
$day+=($number*7);
            break;
        case 
"h":
            
$hours+=$number;
            break
        case 
"n":
            
$minutes+=$number;
            break;
        case 
"s":
            
$seconds+=$number
            break;            
    }
       
$timestampmktime($hours,$minutes,$seconds,$month,$day,$year);
    return 
$timestamp;
}

?> 

We can save that code as dateadd.inc and then start the next code:

<?php

include("dateadd.inc"); 
$temptime time();
echo 
strftime("%Hh%M %A %d %b",$temptime);
$temptime DateAdd("n",50,$temptime);
echo 
"<p>";
echo 
strftime("%Hh%M %A %d %b",$temptime);

?> 

Its returned value is:


15h41 Saturday 03 Jun 16h31 Saturday 03 Jun

15h41 Saturday 03 Jun 16h31 Saturday 03 Jun

DateDiff function creating on PHP

Function syntax is:


DateDiff(interval,date1,date2)

Intervals used by that function are the same as in the DateAdd function. In our example we won’t use additional arguments of the DateDiff function. Intervals that we are going to allow are: w", "d&q", "h", "n" and "s".

<?php

Function DateDiff ($interval,$date1,$date2) {
    
// Gets the amount of seconds between two dates 
    
$timedifference $date2 $date1;

    switch (
$interval) {
        case 
"w":
            
$retval bcdiv($timedifference,604800);
            break;
        case 
"d":
            
$retval bcdiv($timedifference,86400);
            break;
        case 
"h":
            
$retval =bcdiv($timedifference,3600);
            break
        case 
"n":
            
$retval bcdiv($timedifference,60);
            break;
        case 
"s":
            
$retval $timedifference;
            break;
            
    }
    return 
$retval;

}
?> 

We can save that code as datediff.inc and then start the next code:

<?php

include("datediff.inc";
include(
"dateadd.inc");
$currenttime time();
echo 
"Current time: ".strftime("%Hh%M %A %d %b",$currenttime)."&lt;br&gt;";
$newtime DateAdd("n",50,$currenttime);
echo 
"Time plus 50 minutes: "strftime("%Hh%M %A %d %b",$newtime)."&lt;br&gt;";
$temptime DateDiff("n",$currenttime,$newtime);
echo 
"Interval between two times: ".$temptime;

?> 

In the case of correct configuration it shows the following result:

Current time: 16h23 Saturday 03 Jun
Time plus 50 minutes: 17h13 Saturday 03 Jun
Interval between two times: 50 

If you have UNIX system you have to carry out the compilation with bcmath function support.


 

  • Top