Home
Home Page
XML on the screen of a browser
Interaction with life cycle of page
How to overtake competitors and at once to do{make} liderskie pages
Adjustment of parameters PHP in php.ini
KHehshirovanie passwords in PHP
Total Automation of Reception of payments on a site
Object-oriented programming, classes in PHP
Abstract classes and interfaces
The module of definition of a geographical position on IP - mod_GeoIP
Conclusion of messages to the user in webs - applications.
Manipulation date on PHP
The truth about Sessions
Realization of patterns on PHP.
Protection against a spam on a site
Imitation of files and directories
Door in protection: the post web - interface
Safety of search engines in the corporate environment
CHPU and PHP (revisited)
Links
 
 

Manipulation date on PHP

As that time when I wrote a certain similarity of the program of management of the center of support, I have noticed, that I need to count, have what is the time passed since that moment when who that has last time contacted the client about the decision of his  problem. In the past when I used ASP, the decision was simple - in ASP there is function DateDiff which takes two dates and seconds days, months, etc. can say to you how much has passed between them, how much. After viewing some auxiliary editions (that is manuals) on PHP, I have noticed, that he  does not have such function. Then I also have decided to write this clause{article}.


Those questions which we shall discuss in this clause{article}:


1. Reception of current time and date what opportunities at us is?

2. Change of a kind of displayed date - formatting of date and time;

3. Converting existing dates in UNIX time;

4. Back in the future - updating of date

* Addition of time to the current date

* A conclusion of time from the current date

* Reception of time between two dates

5. Creation of function DateAdd for PHP;

6. Creation of function DateDiff for PHP.



Reception of current time and date


UNIX machines declare time as follows - they count up seconds gone since night January, 1-st 1970 - ogo year. It is called EHpoxoj UNIX. So, if we have PHP a code similar to this:



<? php

echo time ();

?>


He will return approximately such result:


958905820


This same, as 12 hours of 43 minutes of Sunday 21 - ogo May, 2000


You will say, what is it very well, but than it will help us? Well actually the urgency is low. Many of function which manipulate date in PHP demand time, which is returned with function time (). And more, as PHP uses time in the identical image both on UNIX and on Windows platformax it to you allows to use a code on any of platformax without kakix or problems. One more advantage will be, that as function time () returns an integer, you can store{keep} it  as is in base dannyx or in a text file - there is no more need for xranenija date / time in otdel`nyx jachejkax a database.


Well, now, when you know as why about UNIX time, we can proceed{pass} to rather important things and we can start to use it for something suitable.



Change of a kind of displayed date - formatting of date and time


PHP gives you two ways of change UNIX of time in something useful. The first is function named date (). At this function two arguments - a line which defines{determines} formatting which should be returned, the second - UNIX time. The line of formatting is some special symbols which display those parts of date and time which you want. We shall present, that we need to display date in such kind " 18h01 Sunday 21 May "


We should use one of special symbols for everyone changed{changeable} a bat in line - you can read about it in a management{manual} on PHP, in section function.date.html. Takix symbols a little which will return the data of type - day of week, a name of month, year in two-digital or chetyrexcyfrovom a format. The following will be necessary for this example for us:


* ' H ' - will return o'clock in the afternoon in 24-x a hour format

* ' i ' - will return minutes

* ' I ' - will return day of week (the long form)

* ' d ' - will return day of month

* ' F ' - the full name of month


Our line will be approximately similar on " Hhi l d F ", hence, code PHP will have the following kind:



<? php

echo date (' Hhi l d F ', time ());

?>


If we shall start this code, we shall receive the following:


180609 Sunday 21 May


That it seems little bit strange before we have seen in a management{manual} on PHP and have learned{have found out}, that h in the bottom register designates time in 12 hour format. The old saying " the Computer does{makes} that you speak him, instead of that from him  achieve " speaks the truth. At us two vyxoda. The first it to bypass h in the bottom register and to write the following:



<? php

echo date (' Hhi l d F ', time ());

?>


Which result of performance will be: 18h12 Sunday 21 May


It can seem to a little more complex , but imagine, that you actually xoteli to see was " Today Sunday 21 May 2000. Time somewhere is close to 18h24. " Use of the command of date in this case would be a little razdrazhajuhhe.


Earlier I have mentioned, that there are two ways for reception something useful from UNIX time. We have just seen date () and strftime (). One more function is getdate (). It is necessary for this function only UNIX time as argument, and she returns an associative file of elements in date.


For example:



<? php

$date_time_array = getdate (time ());

echo $date_time_array [' weekday '];

?>


Will return:


Sunday


Except for "weekday", other parts of a file are:


* "seconds" - seconds

* "minutes" - minutes

* "hours" - hours

* "mday" - day of month

* "wday" - day of week in a numerical format

* "mon" - month in a numerical format

* "year" - year

* "dyear" - day of year in a numerical format

* "month" - a full name of month


Now we can create readable forms of date and time:


But how about movement in the other direction?



Transformation of existing dates in UNIX time


Often you can have necessity to work with the data, which already naxodjatsja in some format of date and time. I have opened base dannyx moix clients Microsoft Access and have found out, that all dates there are established in format GGGG/MM/DD, it means, that input of the current date will be displayed as 2000/05/27. Function mktime () can take values otdel`nyx parts of date and transform ix in UNIX time.


Format of function the following:



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


At the left on the right - you provide hour, minutes, seconds, month, day, year. Whether last argument defines{determines} naxodites` you in time of the savings of a daylight whether or not. This argument is additional and for simplicity we shall lower{omit} it .


The script will have such kind.



<? php

echo mktime (0,0,0,5,27,2000);

?>


I have inserted zero instead of one hour, and second as we ix do not know minute also you should that that there to put. The insert of zero will give us midnight, that as a matter of fact is perfect. Certainly, now you will say (and will be right), that I have deceived also itself have put there zero. Then let's make once again, yes so that the script itself understood as where to put.



<? php


$access_date = ' 2000/05/27 ';


// Function explode () breaks a line in other line. In this case

// $access_date it is broken on a symbol/


$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]);

?>


Good let's a little complicate and it is imaginable, that instead of reception simply dates from database Access, we have received date and time in such format:


2000/05/27 02:40:21 PM



<? php


// A line received from Access

$date_time_string = ' 2000/05/27 02:40:21 PM ';


// Splitting a line in 3 parts - date, time and AM/PM

$dt_elements = explode (' ', $date_time_string);


// Splitting date

$date_elements = explode (' / ', $ dt_elements [0]);


// Splitting time

$time_elements = explode (': ', $ dt_elements [1]);


// If at us time in format PM we can add 12 hours for reception 24 hour formats of time

if ($dt_elements [2] == ' PM ') {

    $time_elements [0] + = 12;

}


// A conclusion of result

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


?>



Change of date


Often it is required to us what is the time will learn{will find out} in 6 hours what was day of week 35 days ago, or how much seconds have passed since that moment as you last time played Quake3. We already saw as function mktime () can be used for generation UNIX of time from otdel`nyx elements of date and time. And how we shall act{arrive} if we will need to receive UNIX time from the current date and time? Little bit senseless exercise, but it will help with an illustration of that we shall do{make} in the future.


As we have seen, function mktime () accepts the following arguments: hour (hour), minute (minute), second (second), month (month), day (day), year (year). And if you once again see the previous paragraphs will see, that function getdate () can give us all these parts and bats:



<? php


// Takes away current time in a file

$timestamp = time ();

echo $timestamp;

echo ' <p> ';

$date_time_array = getdate ($timestamp);


// Use mktime for updating UNIX of 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;

?>


Looks not so. We shall add a pair peremennyx that all became more understandable:



<? php


// Takes away current time in a file

$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 of time

$timestamp = mktime ($hours, $minutes, $seconds, $month, $day, $year);

echo $timestamp;


?>


Now, when we have taken the information from a file which has been created by function getdate (), and have placed in accordingly named variables, a code became more understandable and began easily we read. Now if we need to add 19 hours by current time instead of adding $hours to mktime (), we can simply write the following $hours +19. Function mktime () itself will make perexod next day.



<? php


// Takes away current time in a file

$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 of time

// Addition of 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';


?>


Job of this script will display:


14h58 Saturday 03 Jun

09h58 Sunday 04 Jun

~E after adding 19 hours


Subtraction of time is made by precisely same way - simply take from a variable that part, which you xotite.


Calculation of a difference between two parameters of time too is pertinent. All that to you neobxodimo for this purpose to transform both parameters in UNIX time and simply to deduct one of another. The result will be distinction in sekundax between two from time to time. Fast arithmetics can transform seconds to days, hours, minutes and seconds.



Creation of function DateAdd for PHP


As I already spoke in the beginning - the reason of a spelling of this clause{article} was that I could not find in PHP function similar DateDiff in ASP. Now, when we have explained as PHP works with date and time, it would be convenient to import in PHP two functions of job with date used in ASP. The first is function DateAdd.


Interval is the line expression, a determining interval which you xotite to add. For example minutes or days, number{room} it is an interval which you want to add, and date and there is a date.


Interval can be one of underwritten:

yyyy year

q a quarter

q a quarter

m month

y day of year

d day

w day of week

ww week of year

h hour

n minute

s second


Here w, y and d do{make} same, namely add 1 day by the current day, q adds 3 months, 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;           

}

       $timestamp = mktime ($hours, $minutes, $seconds, $month, $day, $year);

    return $timestamp;

}


?>


We can soxranit` this code under a name dateadd.inc then start the following 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);


?>


Returned which value will be:


15h41 Saturday 03 Jun

16h31 Saturday 03 Jun

Creation of function DateDiff for PHP


According to the documentation function DateDiff " Returns quantity{amount} of intervals between two dates ".


Syntax of function is those:


DateDiff (interval, date1, date2)


Intervals which this function uses the same, that we have seen in job with function DateDiff. For the sake of simplicity we shall reject set of elements of function DateDiff VB of scripts which differently would complicate jobs. In this example additional arguments of function DateDiff (whether determining week begins with Monday or Sundays) are not used. Intervals which we are going to resolve the following - "w", "d*q", "h", "n" and "s".


Let's see, that we can make:



<? php


Function DateDiff ($interval, $date1, $date2) {

    // Receives quantity{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;


}

?>


After preservation of this code under a name datediff.inc, we can start the following code:



<? php


include (' datediff.inc ';

include (' dateadd.inc ');

$currenttime = time ();

echo ' Current time: '.strftime (' %Hh%M %A %d %b ', $currenttime). ' And lt; br*gt; ';

$newtime = DateAdd (' n ', 50, $currenttime);

echo ' Time plus 50 minutes: '. strftime (' %Hh%M %A %d %b ', $newtime). ' And lt; br*gt; ';

$temptime = DateDiff (' n ', $currenttime, $newtime);

echo ' Interval between two times: '. $ temptime;


?>


Which, in case of correct konfigurirovanija, should display the following:


Current time: 16h23 Saturday 03 Jun

Time plus 50 minutes: 17h13 Saturday 03 Jun

Interval between two times: 50


If at you the system compilation to you will need to be made with support for bcmath functions is established UNIX. File README.BCMATH in your distribution kit will give all necessary details. And PHP4 for Windows platforms can make bcmath calculations without special additives.