How to use Date and Time in PHP
HOW TO USE DATE AND TIME IN PHP:
PHP time and date function informs us about current date and time. it can be manipulated also.
How time() function works:
The time() function would work by our server time and can be changed. It returns integer but not the argument. Date and time are stored in computer in UNIX Timestamp format. That calculates time in number of seconds on GMT ( greenwich mean time) i.e January 1,1970.
Syntax:
<?php Print time(); ?>
Output: 1532423507
EXAMPLE:
<!DOCTYPE html> <html lang="en"> <head> <title>READABLE TIME</title> </head> <body> <?php /* Return current time*/ $actualtime = time(); echo($actualtime); ?> </body> </html>
How date() function works:
In PHP, date() function shows day, month and year altogether. Date and time are stored in computer in UNIX Timestamp format. That calculates time in number of seconds on GMT ( greenwich mean time) i.e January 1,1970.
Syntax:
<?php $today =date(“d/m/y”); Echo $today; ?>
Output: 24/07/2018
Methods for PHP Date and Time:
- checkdate(): this clears the date and year exists or not.
Example:
<?php var_dump(checkdate(12,31,-400)); echo "<br>"; var_dump(checkdate(2,29,2003)); echo "<br>"; var_dump(checkdate(2,29,2004)); ?>
Output:
bool(false) bool(false) bool(true)
2. dateadd(): this method is used to add the days, months, years to the date.Example:
<?php $date=date_create("2013-03-15"); date_add($date,date_interval_create_from_date_string("40 days")); echo date_format($date,"Y-m-d"); ?>
Output: 2013-04-24
3. datecreate(): it returns new datetime .Syntax:
date_create(time,timezone);
Example:
<?php $date=date_create("2013-03-15 23:40:00",timezone_open("Europe/Oslo")); echo date_format($date,"Y/m/d H:iP"); ?>
Output: 2013/03/15 23:40+01:00
Recasting a Time Stamp with getdate() function:
The function getdate() takes a time stamp and associative array is returned and all the information about date is embedded in it. the time stamp is optionally working instead current time stamp is used that returned by time().
Example:
<?php $date_array = getdate(); Foreach ($date_array as $key =>$val ) { Print “$key =$val<br/>”; } $formatted_date=”$today’s date”; $formatted_date =”$date_array”[monday]; $formatted_date =”$date_array”[mon]; $formatted_date =”$date_array”[year]; Print $formatted_date; ?>