PHP dates and times


time() function returns the current time in the number of seconds since the Unix Epoch (January 1 1970 00:00:00 GMT)

Epoch time = Unix timestamp

The valid range of a timestamp correspond to the minimum and maximum values for a 32-bit signed integer, for example
zero = January 1 1970 00:00:00
32bit = timestamp from Dec 1902 to Jan 2037.
64bit = billion of years


mktime() – Returns the Unix timestamp corresponding to the arguments given.
mktime($hour, $minute, $second, $month, $day, $year)
Arguments may be left out in order from right to left; any omitted argument will be replaced with the current value according to the local date and time.


mktime() – Tries to convert any string passed into a unix timestamp. Returns a timestamp on success, FALSE otherwise

echo strtotime("now");

echo strtotime("15 February 2019");

echo strtotime("february 15 2019");

echo strtotime("+1 day");

How to create a Unix timestamp?

Uses one of these 3 functions:

  • time()
  • mktime()
  • strtotime()


checkdate() Checks the validity of the date formed by the arguments. Returns TRUE if the date given is valid; otherwise returns FALSE.

checkdate($month, $day, $year)

echo checkdate(2,29,2019) ? 'true' : 'false';

echo checkdate(2,29,2019) ? 'true' : 'false';

Format a Unix timestamp

To format a unix timestamp uses one of the functions:

  • date($format, $timestamp) – Returns a string formatted according to the given format string using the given integer timestamp or the current time if no timestamp is given.
    Timestamp is optional and defaults is the the value of time()
  • strftime($format, $timestamp) – Format the time and/or date according to locale settings. Month and weekday names and other language strings respect the current locale set with setlocale() function.
    Timestamp is optional and defaults is the current local time.
    setlocale() – Sets locale information.

    $timestamp = time();
    echo strftime("Today is %m/%d/%y",$timestamp);
    //Today is 04/23/19  

Format to MySql datetime

$timestamp = time();
$mysql_datetime = strftime("%Y-%m-%d %H-%m-%S",$timestamp);
echo $mysql_datetime;  
//2019-04-24 01-04-38 

Leave a Reply

Your email address will not be published. Required fields are marked *