Getting current time php. Php working with dates - date DateTime mktime and others...
Let's look at some of the code from a real web page, and create our first PHP script, namely, display the date and current time on our website. This script is used quite often on websites and I think it will be useful to many.
Let's create another php file and call this file time.php. We studied it earlier, if you forgot, repeat it.
So we created the time.php file and placed this file in the previously created myphp folder at . We studied this topic in the lesson
Open the code of the time.php file and between the tags
And write the following code: Listing 1:Listing 1.
Today: |
Let's launch Local server, dial in address bar browser address http://localhost/myphp/time.php and press Enter. And we see this picture:
Please note that in in this case the current server time is displayed, those. if, for example, the server on which your site “lives” is located in another country and the current time differs from Moscow, then the displayed time value will also differ from Moscow.
Let's look at the code Listing 1. Regular text labels "Today" And " Current time" are not processed by the PHP preprocessor and are output as "is". Instead of these entries, you can write any text, for example just date or Time etc.
And here is the php code enclosed in descriptorsBefore being given to the browser, it undergoes PHP processing.
As you probably already understood, the date function in PHP responsible for outputting date and time. IN parentheses Date and time display values are indicated. There are a lot of such values in PHP, and we will devote the next separate lesson to this analysis and study of all possible values.
The echo operator is translated as withdraw, in this case we mean display on the monitor screen Date And Server Time.
The same result (display in the browser) can be achieved by placing the entire script inside PHP descriptors. Look Listing 2:
Listing 2.
echo "Today:" ; |
All text elements intended for output must be enclosed in quotation marks. Text strings can be enclosed in both single and double quotes, we'll talk about the difference later. Posts:
echo "Today" ;
echo "Today" ;
are completely equivalent and will appear the same.
The space character before the closing quotation mark is used to separate the output of the date function from the surrounding text. All commands in PHP are always separated by a semicolon.
To display the Date and Time on the site, insert the code Listing 1 or Listing 2 to the right place on your web page. To add inscriptions (Date and Time) general style website design, you can use.
P.S. I remind you that the file in which you place PHP inserts
must have the extension .php and, in addition, the hosting on which your site “lives” must support PHP (today this is almost all It is obvious that very often programmers have to work with date and time . The simplest example is the date and time a message was sent on a forum. And, of course, such things can be realized on PHP , especially since there are opportunities for working with date and time in PHP
so many. Basic function related to date and time in PHP , - This time() function , which returns the number of seconds that have passed since midnight 01/01/1970 (the birth of the era):
Unix
?>
echo time(); , which returns the number of seconds that have passed since By running this script, you will find out how many seconds have passed since until the moment of the call time() functions
in your script. Of course, besides this basic function It is obvious that very often programmers have to, which is present in all programming languages where you can (at least among the ones I know) there is another function called:
getdate()
$datetime = getdate();
foreach ($datetime as $k=>$v)
";
?>
echo "$k - $v By running this script, you will see a set of keys in the array and their corresponding values (at the same time, we repeated the construction foreach ). I think that now it will not be difficult for you to find out any data related to date and time
getdate()
. For example, to display the current time, you would write the following code:
?>
echo $datetime["hours"]..":".$datetime["minutes"]..":".$datetime["seconds"]; Also getdate() functions , which returns the number of seconds that have passed since there is an optional parameter which means the number of seconds that have passed since
. It is made so that this function can return not only the current time and date, but, generally speaking, any:
$datetime = getdate(152353232);
?>
echo $datetime["year"]; As a result, you will see 1974
year. There is also date() function . I recommend looking at the description of it in the reference book, since accepts a very complex parameter that specifies the date output format. There are a little more than 30 formatting elements. And in the example below I will give a few of them, and look at the rest in the reference book, because you don’t need to memorize them, but it is highly advisable to familiarize yourself with them. But it is necessary to know the principle of their use, and the following example about it:
echo date("Today d.m.Y H:i:s");
?>
As a result, you will see something like this: " Today 11/15/2010 21:44:24". Also date() functions There is also a second optional parameter that specifies timestamp, exactly the value equal to the number of seconds that have passed since , which returns the number of seconds that have passed since. Example of using the second parameter:
echo date("Once upon a time there was d.m.Y H:i:s", 5393235329);
?>
year. gmdate() function, which is a complete analogue date() functions, But gmdate() function shows the time not according to the time zone of the server on which the script is running, but according to Greenwich. Obviously, using this function you need to save all the information about the date and time that the user sees, and when outputting you need to adapt to the time zone of each user (ideally, of course):
echo gmdate("Now in Greenwich D M j H:i:s T Y")
?>
As a result, you will see something like this: " Mon Nov 15 18:52:45 GMT 2010"Of course, you will see a different date, but in a similar format. I also strongly recommend that you go into the reference book and just familiarize yourself with the other date and time elements in . The simplest example is the date and time a message was sent on a forum. And, of course, such things can be realized on(I gave only a third), since date() and gmdate() functions- this is the simplest and most quick way get date and time in almost any format.
JavaScript is blocked in your browser. Please enable JavaScript for the site to function!
Date and time representation
IN distributed systems, such as the Internet, time plays a special role. Due to a slight discrepancy in the system clock, a Forex player can lose tens of thousands of dollars within minutes; the business intelligence system will make a mistake in making a forecast; NNTP servers will lose during synchronization important information, needed by the user etc.
PHP contains many functions for working with date and time. The most used are:
- time()- returns the current absolute time. This number is equal to the number of seconds that have passed since midnight on January 1, 1970 (since the beginning of the UNIX era).
- (at least among the ones I know) there is another function called- reads date and time information. Returns associative array, containing information for the specified or current (by default) time. The array contains the following elements:
Example 1
Using getdate() $val) echo "$key = $val
"; echo "
Today: $d.$d.$d"; ?>RESULT OF EXAMPLE 1:
Seconds = 21 minutes = 4 hours = 12 mday = 10 wday = 4 mon = 11 year = 2005 yday = 313 weekday = Thursday month = November 0 = 1131613461 Today: 11/10/2005
- date()- date and time formatting. Arguments: format string and absolute time. The second argument is optional. Returns a string with the given or current date in the specified format. The format string may contain the following codes:
a A "AM" or "PM" designation included d Day of the month (01-31) D Abbreviated name of the day of the week (three letters) F Full month name g Clock (12-hour format without leading zeros) G Clock (24-hour format without leading zeros) h Clock (12 hour format) H Clock (24-hour format) i Minutes (00-59) j Day of the month without leading zeros (1-31) l Full name of the day of the week L Leap year indicator (0 or 1) m Month (01-12) M Abbreviated month name (three letters) n Month (1-12) s Seconds (00-59) t Number of days in a given month (from 28 to 31) U Absolute time w y Year (two ranks) Y Year (four ranks) z Day of the year (0-365) Z Time zone offset in seconds (-43200 to 43200) Any other information included in the format string will be inserted into the returned string. If you need to add characters to the format string that are themselves format codes, then they must be preceded by a backslash "\". Characters that become format codes when appended with a backslash must be preceded by two forward slashes. For example, if you need to add "n" to a string, you must enter "\\n" since "\n" is a newline character.
Example 2
Using date() RESULT OF EXAMPLE 2:
Today: 10.11.05 13:03
- mktime()- returns the absolute time, which can then be used with the date() or getdate() functions. Takes up to six integer arguments in the following order:
Watch
minutes
seconds
month
day of the month
yearExample 3
Using mktime() RESULT OF EXAMPLE 3:
- checkdate()- checking the correctness of the date. Arguments: month, day, year. Returns true if the date is correct, i.e.
month - an integer from 1 to 12;
day is an integer not exceeding the total number of days in a given month. In this case, leap years are processed correctly;
year is an integer from 1 to 32767.For example:
If (!checkdate($month, 1, $year)) ( $d = getdate(); $month = $d; $year = $d; )
Attention! The date may be within a valid range, but other date functions will not accept the value. Thus, mktime() should not be used for years before 1902, and should be used with caution for years before 1970.
- strftime()- formation of local date and time. Arguments: format string and absolute time. The second argument is optional. Returns a string with the given or current date in the specified format. In this case, the names of months and days of the week are extracted from the locale selected using the function. The format string may contain the following codes:
%a Abbreviated name of the day of the week %A Full name of the day of the week %b Abbreviated month name %B Full month name %c Preferred date and time format %C Century number %d Day of the month (1-31) %D Same as %m/%d/%y %e Month (1-12) %h Same as %b %H Clock (24-hour format) %I Clock (12 hour format) %j Day of the year (0-365) %m Month (1-12) %M minutes %n Newline character %p "am" or "pm" notation included %r Time using a.m./p.m. notation %R Time in 24 hour format %S Seconds (00-59) %t Tab character %T Same as %H:%M:%S %u Number of the day of the week (1 - Monday, 7 - Sunday) %U Week number. The countdown begins on the first Sunday of the year %V Week number according to ISO 8601:1988. The first week must have at least four days, and Monday is considered the first day %W Week number. The countdown starts on the first Monday of the year %w Number of the day of the week (0 - Sunday, 6 - Saturday) %x Preferred date format without time %X Preferred time format without date %y Year (two ranks) %Y Year (four ranks) %Z Time zone (name or abbreviation) %% Symbol "%" Any other information included in the format string will be inserted into the returned string.
Working with date and time in PHP is relatively easy. Availability is quite large quantities functions makes the code less cumbersome (and in PHP 5.2 with the advent of DateTime and in 5.3 with the addition of the DateInterval and DatePeriod classes and individual methods, working with dates has become even simpler and more convenient). So, to work with the date... First, in any case, you should keep in mind that:
- almost any action can be done in several ways;
- all code is written for demonstration and work examples;
- The proposed alternative result may not always be suitable when using more early version PHP (sometimes easier than editing working code from many years ago);
In PHP 5.3 for correct operation dated to avoid Strict Standards errors. Today, as a rule, this situation is taken into account either in scripts or in hosting settings.
PHP convert UNIX timestamp to date in given format
One of the most simple tasks. The function used is: date($format, $time)
The first parameter is passing the date format - for more details, see the documentation (for the “usual one” 28.02.2012 15:43:59
should be used:
date("d.m.Y H:i:s", $time)
PHP how to find out tomorrow/yesterday's date
Everything is simple here too. Time function() we get the current time in UNIX Timestamp format. Subtract (yesterday's date) or add (tomorrow) required quantity seconds (86400 = 3600*24 - in days) and we get:
$now = time(); // not required
$yesterday = time()-3600*24;
$tomorrow = time()+3600*24;
$weekBefore = time() - 3600*24*7; // a week ago
echo "Yesterday: ",date("d.m.Y", $yesterday),"
Tomorrow:",date("d.m.Y",$tomorrow);
PHP how to get a date with a specific offset (X days earlier/later)
Sometimes you need to find out a date that will be several days from the specified one. For example, the user paid for the service on February 11, 2013 for 3 weeks. Payment information is available. Until what date is it paid?
When you can “just” add a couple of days and get February 13, the procedure does not cause any particular difficulties. But what about different amounts days in a month? What about leap years? Everything has already been invented before us - to calculate the date from a known interval we will use mktime
$payment = array("day"=>11,"month"=>2,"year"=>2013);
$toDate = mktime(0,0,0,$payment["month"],$payment["day"]+3*7,$payment["year"]);
echo date("d.m.Y",$toDate); // conclusion
// in PHP > 5.3 using DateInterval
date_default_timezone_set("Europe/Moscow");
$datetime = new DateTime(date());
$datetime->sub(new DateInterval("P7D")); // minus 7 days
PHP how to calculate the difference between dates
It would seem simple situation- there are two dates, count the number of days (months and days) between them. However, a “manual” implementation will take some time, and there is a chance of missing something (for fun - those who want to try can leave the code in the comments). PHP has a built-in date_diff function to calculate the difference between dates, or more precisely Datetime::diff
$datetime1 = new DateTime("2013-05-01");
$datetime2 = new DateTime("2013-01-01");
$interval = $datetime1->diff($datetime2);
echo $interval->format("%R%a days after New Year");
PHP convert DDD days to X years Y months Z years
Sometimes you need to display the time after a certain event. For example, after registration it passed. For convenience (3200 days doesn’t mean much), perception can be converted into years and months using DateInterval::format formatting
$registerDate = new DateTime("2009-03-03");
$today = new DateTime();
$interval = $today->diff($registerDate);
echo "Elapsed since registration: ";
echo $interval->format("%a days")."\n"; // total number of days
echo "or ";
echo $interval->format("%m months, %d days"); // months, days
PHP translation from date to timestamp - parsing date in Russian format
Sometimes you need to convert a date in a format that is easy to read into the UNIX TIMESTAMP format. To parse a date in the format '2013-05-30 12:35' into its components (separately get the year, month, day), you can use the date_parse function. To convert directly to unix timestamp, you can use strtotime (as well as variations like 'now', '+1 day', 'next Thursday' - php.net/manual/en/datetime.formats.php):
echo strtotime("2013-05-30");
print_r (date_parse("2013-05-30 12:35"));
However, for Russia the more familiar format is DD.MM.YYYY. You can, of course, split the date by the period symbol, get the day, month, year, and use the mktime function to find out the corresponding UNIX TIMESTAMP value. PHP5.3 introduced the date_parse_from_format function, into which you can pass a format string. And for PHP5.2 I used strptime (the existence of which, as it turned out, not everyone is aware of, perhaps because it is simply not implemented for Windows: This function is not implemented on Windows platforms):
$date = "05/30/2013 12:35";
$format = "d.m.Y H:i";
print_r (date_parse_from_format($format,$date));
// Alternative option for PHP5.2
$format = "%d.%m.%Y %H:%M"; // different from the one used in the date function
$d = strptime($date, $format);
$newDate = mktime($d["tm_hour"], $d["tm_min"], $d["tm_sec"],
$d["tm_mon"]+1, $d["tm_mday"], $d["tm_year"]+1900); // tm_mon 0-11, tm_year 1900
echo $newDate;
In addition, the strptime function has special features - the month is shifted by one (January - 0), and the year is the number of years since 1900, i.e. for 2013 $d[’tm_year’] will be equal to 113.
Links and helpful information:
PHP dateTime functions http://www.php.net/manual/en/ref.datetime.php - functions for working with date
PHP class DateTime http://www.php.net/manual/en/class.datetime.php
PHP date_diff http://www.php.net/manual/en/function.date-diff.php
PHP strftime http://ru2.php.net/manual/en/function.strftime.php
PHP date_parse_from_format http://ru2.php.net/manual/en/function.date-parse-from-format.php
Among various programming tasks, various manipulations with date and time values are quite common. Rare automated system, the database can do without storing information about the time of a particular process. In addition to simply adding a date to a database record or displaying this date, there are many tasks to display these dates in in various forms, checking whether the current time matches set timer, calculating the period between two dates and much more.
For the convenience of working with dates, each programming language has its own special types data to store date and time values. Most often this numeric value, either integer or floating point.
IN PHP work with a date it most often encounters UNIX TIMESTAMP. Here the time is stored as an integer. The calculation of time begins on January 1, 1970. Therefore, for example, the date and time 12/11/2014 19:40:00 would be represented by the number 1418316000. This number shows how many seconds have passed since the zero date of January 1, 1970, called the Unix Epoch.
An example of a PHP page that provides data conversion capabilities is presented on the website in the programs section with the program "Convert date and time format". Here you can generate the desired date in the UNIX TIMESTAMP format, as well as bring this format into a standard, human-readable form.
Getting current time and date in PHP
To get the current server time, use the function
int time(void)
which will just return the value in unix format timestamp.
echo time(); // output the current time in unix timestamp format
At first glance not very convenient format for a person, but, as is known, than simpler presentation data, the faster the computer processes these values. Also, storing a number in a database is much more cost effective than any special format. Also, PHP works the same over time on both Unix and Windows platform, which makes it possible to use the code on any of these platforms.
Convert date and time format in PHP
The simplest mechanism for converting a numeric date value into more understandable values is provided by the function:
array getdate()
It returns an associative array containing date information. If the timestamp parameter is not specified, the current time will be returned. This array contains the following values:
The resulting array allows you to display the values in the desired form:
$date = 1418372345;
$date_mas = getdate($date);
echo $date_mas["mday" ] . " . " . $date_mas["mon" ] . " . " . $date_mas["year" ]; // 12.12.2014
You can also use the function to convert the date and time format:
string date(string $template [, int $unix_timestamp])
It is intended to obtain the current unix dates timestamp in in the required format. The $template string parameter specifies the output format. The $unix_timestamp parameter can be used to specify which time value to work with. It is optional, so if it is not specified it will be used The current date and time.
The format is specified by the following values:
a | "before" and "after" noon: "am" or "pm" |
A | "before" and "after" noon in capital letters: "AM" or "PM" |
d | day of the month in 2 digits (if less than 10, zero comes first) (01 to 31) |
D | day of the week in 3 letters. For example, "Mon" (Monday) |
j | day of the month, 1-2 digits without leading zeros (from 1 to 31) |
F | name of the month. For example, "January" |
h | hour, 12-hour format (01 to 12) |
H | hour, 24-hour format (00 to 23) |
g | hour, 12-hour format without zeros (1 to 12) |
G | hour, 24-hour format without zeros (0 to 23) |
i | minutes (00 to 59) |
I (capital i) | 1 if the transition to summer time, otherwise 0 |
L | 1 if the year is a leap year, or 0 if it is not a leap year |
B | time in Internet time format ( alternative system time of day countdown) (from 000 to 999) |
T | computer time zone. For example, MDT |
l (lowercase L) | day of the week. For example, "Monday" |
m | month, two digits with zeros (01 to 12) |
n | month, one or two digits without zeros (from 1 to 12) |
M | abbreviated name of the month. For example, "Jan" |
t | number of days in the specified month (from 28 to 31) |
s | seconds (0 to 59) |
S | English two-letter ordinal number suffix ("st", "nd", "rd" or "th") |
U | integer number of seconds since the start of the UNIX epoch |
y | year, digital, 2 digits (14) |
Y | year, digital, 4 digits (2014) |
z | ordinal number of the day in the year (from 0 to 365) |
Z | time zone offset in seconds (from -43200 to 43200) |
N | serial number of the day of the week from 1 (Monday) to 7 (Sunday) in accordance with the ISO-8601 standard, (added in PHP 5.1.0) |
w | serial number of the day of the week from 0 (Sunday) to 6 (Saturday) |
W | serial number of the week of the year in accordance with the ISO-8601 standard; weeks start on Monday (added in PHP 4.1.0) |
o | year number according to ISO-8601 standard. Has the same meaning as Y, except when the ISO week number (W) is from the previous or following year; then the year of that week will be used. (added in PHP 5.1.0) |
e | time zone scale code. For example: UTC, GMT, Atlantic/Azores (added in PHP 5.1.0) |
O | difference with Greenwich time, in hours. For example: +0200 |
P | difference from Greenwich Mean Time with a colon between hours and minutes. For example: +02:00 (added in PHP 5.1.3) |
c | date in ISO 8601 standard format. For example, 2014-12-12T15:19:21+00:00 (added in PHP 5) |
r | date in » RFC 2822 format. For example: Thu, 21 Dec 2000 16:01:07 +0200 |
U | number of seconds that have passed since the beginning of the Unix Epoch (The Unix Epoch, January 1, 1970 00:00:00 GMT) |
As you can see from the list, you can get a lot of useful date data using this function. For example:
$date = 1418372345; // initial date and time 12/12/2014 11:19:05
echo date("d.m.Y" , $date); // 12.12.2014 (date)
echo date("H:i:s" , $date); // 11:19:05 (time)
echo date("H:i" , $date); // 11:19 (time)
echo date("t" , $date); // 31 (number of days in a month)
echo date("z" , $date); // 345 (ordinal number of the day in the year)
echo date("l dS \of F Y h:i:s A" , $date); // Friday 12th of December 2014 11:19:05 AM
Other characters included in the pattern will be printed as is on the line. If you need to enter a character that is used in a function as a format code, the “\” character is inserted in front of them. For the value "\n" (the transition character new line), you should specify "\\n". Thus, you can output an entire message containing date and time information:
echo date( "Today is the zth day of the yth year", $date); // Today is the 345th day of 2014
Convert date and time to timestamp format
To reverse date conversion from standard format The function is applied to the numeric timestamp value:
int mktime(]]]]]])
The mktime() function returns the Unix time value corresponding to the date and time specified by its arguments. For example:
$my_date = mktime(10, 30, 0, 12, 12, 2014);
You should be careful about the order of the function arguments: hours, minutes, seconds, month, day, year.
Except simple formation date values in timestamp, the mktime() function can be used to perform arithmetically with dates. To do this, you can simply enter the necessary arguments. For example, if you specify the 14th month, then in the final value the month will be the 2nd, and the year value will increase by one:
$my_day = 12;
$my_month = 12;
$my_year = 2014;
$new_date = mktime(0, 0, 0, $my_month + 5, $my_day, $my_year);
echo date("d.m.Y" , $new_date); // 05/12/2015 (date)
You can do the same with other parameters.
Checking date validity in PHP
When working with dates, especially when generating a date using the mktime() function proposed above, it is necessary to take into account the correctness of the entered date. To do this, PHP uses the function:
bool checkdate(int month, int day, int year)
Returns true if the date specified by the arguments is correct; otherwise it returns false. The date is considered correct if:
Year in the range from 1 to 32767;
Month ranges from 1 to 12;
The day for a given month, taking into account leap years, is indicated correctly.
Date checking example:
$my_day = 32;
$my_month = 12;
$my_year = 2014;
if (!checkdate($my_month, $my_day, $my_year))
echo "Error: the date is incorrect";