PHP ─ Date and TimeDates are so much part of everyday life that it becomes easy to work with them without thinking. PHP also provides powerful tools for date arithmetic that make manipulating dates easy. Getting the Time Stamp with time() PHP's time() function gives you all the information that you need about the current date and time. It requires no arguments but returns an integer. The integer returned by time() represents the number of seconds elapsed since midnight GMT on January 1, 1970. This moment is known as the UNIX epoch, and the number of seconds that have elapsed since then is referred to as a time stamp.
<?php
print time(); ?> It will produce the following result:
1468926906
This is something difficult to understand. But PHP offers excellent tools to convert a time stamp into a form that humans are comfortable with. Converting a Time Stamp with getdate() The function getdate() optionally accepts a timestamp and returns an associative array containing information about the date. If you omit the time stamp, it works with the current time stamp as returned by time(). The following table lists the elements contained in the array returned by getdate().
Example Try out the following example.
<?php
$date_array = getdate(); foreach ( $date_array as $key => $val ) { print "$key = $val<br />"; } $formated_date = "Today's date: "; $formated_date .= $date_array[mday] . "/"; $formated_date .= $date_array[mon] . "/"; $formated_date .= $date_array[year]; print $formated_date; ?> It will produce the following result:
second = 6
minutes = 15 hours = 11 mday = 19 wday = 2 mon = 7 year = 2016 yday = 200 weekday = Tuesday monday = July 0 = 1468926906 Today's date:19/7/2016 Converting a Time Stamp with date() The date() function returns a formatted string representing a date. You can exercise an enormous amount of control over the format that date() returns with a string argument that you must pass to it.
date(format,timestamp)
The date() optionally accepts a time stamp if omitted, then current date and time will be used. Any other data you include in the format string passed to date() will be included in the return value. The following table lists the codes that a format string can contain:
Try out the following example.
<?php
print date("m/d/y G.i:s<br>", time()); print "Today is "; print date("j of F Y, \a\\t g.i a", time()); ?> It will produce following result:
07/19/16 11.15:06 Today is 19 20 16f July 2016.at 11.15 am
Hope you have a good understanding of how to format date and time according to your requirement. For your reference a complete list of all the date and time functions is given in PHP Date & Time Functions. |