Epoch Converter and Date/Time in PHP
Quick Navigation
- Get Epoch Seconds
- Convert from epoch to human readable date
- Convert from human readable date to epoch
Getting current epoch time
Time returns an integer with the current epoch:
echo time(); // current Unix timestamp
echo "\n\n";
echo microtime(true); // microtime returns timestamp with microseconds (param: true=float, false=string)
Output:
1550282567
1550282567.0614
Convert from epoch to human readable date
Use the date function or the DateTime class.
//1. Use the 'date' function.
echo "Use the 'date' function.\n";
$epoch = 1483228800;
echo date('r', $epoch); // output as RFC 2822 date - returns local time
echo "\n";
echo gmdate('r', $epoch); // returns GMT/UTC time: Sun, 01 Jan 2017 00:00:00 +0000
echo "\n\n";
//2. Use the DateTime class.
echo "Use the DateTime class.\n";
$epoch = 1483228800;
$dt = new DateTime("@$epoch"); // convert UNIX timestamp to PHP DateTime
echo $dt->format('Y-m-d H:i:s'); // output = 2017-01-01 00:00:00
Output:
Use the 'date' function.
Sun, 01 Jan 2017 00:00:00 +0000
Sun, 01 Jan 2017 00:00:00 +0000
Use the DateTime class.
2017-01-01 00:00:00
In the examples above "r" and "Y-m-d H:i:s" are PHP date formats, other examples can be found here.
You can also use Carbon instead of DateTime. The Carbon documentation is here.
Convert from human readable date to epoch
1. strtotime parses most English language date texts to epoch/Unix Time.
2. The PHP DateTime class is easy to use.
3. mktime is not as easy to use but works on any PHP version.
//1. Using 'strtotime':
echo "Using 'strtotime': \n";
echo strtotime("18 February 2019");
// ... or ...
echo "\n";
echo strtotime("2019/2/18");
// ... or ...
echo "\n";
echo strtotime("+10 days"); // 10 days from now
echo "\n\n";
//2. Using the DateTime class:
echo "Using the DateTime class: \n";
// object oriented
$date = new DateTime('02/18/2019'); // format: MM/DD/YYYY
echo $date->format('U'); //The date format 'U' converts the date to a UNIX timestamp.
echo "\n";
// or procedural
$date = date_create('02/18/2019');
echo date_format($date, 'U');
echo "\n\n";
//3. Using 'mktime':
echo "Using 'mktime': \n";
//mktime ( $hour, $minute, $second, $month, $day, $year );
echo mktime(18, 29, 0, 2, 18, 2019);
Output:
Using 'strtotime':
1550448000
1550448000
1551396801
Using the DateTime class:
1550448000
1550448000
Using 'mktime':
1550514540
Use date_default_timezone_set function to set your timezone.