15

In my PHP program, I'm using $_SERVER to log the page's date visited:

$dateStamp = $_SERVER['REQUEST_TIME'];

The result is that the $dateStamp variable contains a Unix timestamp like:

1385615749

What's the simplest way to convert it into a human-readable date/time (with year, month, day, hour, minutes, seconds)?

ashleedawg
  • 20,365
  • 9
  • 72
  • 105
user4951
  • 32,206
  • 53
  • 172
  • 282

6 Answers6

34

This number is called Unix time. Functions like date() can accept it as the optional second parameter to format it in readable time.

Example:

echo date('Y-m-d H:i:s', $_SERVER['REQUEST_TIME']);

If you omit the second parameter the current value of time() will be used.

echo date('Y-m-d H:i:s');
Syntax Error
  • 4,475
  • 2
  • 22
  • 33
Havenard
  • 27,022
  • 5
  • 36
  • 62
2

Your functional approch to convert timestamp into Human Readable format are as following

function convertDateTime($unixTime) {
   $dt = new DateTime("@$unixTime");
   return $dt->format('Y-m-d H:i:s');
}

$dateVarName = convertDateTime(1385615749);

echo $dateVarName;

Output :-

2013-11-28 05:15:49

Working Demo

Roopendra
  • 7,674
  • 16
  • 65
  • 92
  • @JimThio, Roopenda: The @ sign is not for error suppressing. [It's the format specifier `DateTime` uses for a unix timestamp.](http://www.php.net/manual/en/datetime.formats.compound.php) If it actually did suppress errors, that would be a bad idea anyway. – Boann Nov 28 '13 at 18:54
  • @Roopenda I wasn't saying to remove it. Now you've removed it the code won't work at all. – Boann Nov 28 '13 at 23:13
  • @Boann thanks for update me. I was thought I have done something wrong. – Roopendra Nov 29 '13 at 03:04
1
<?php
$date = new DateTime();

$dateStamp = $_SERVER['REQUEST_TIME'];

$date->setTimestamp($dateStamp);

echo $date->format('U = Y-m-d H:i:s') . "\n";
?>
1

you can try this

<?php
$date = date_create();
$dateStamp = $_SERVER['REQUEST_TIME'];
date_timestamp_set($date, $dateStamp);
echo date_format($date, 'U = D-M-Y H:i:s') . "\n";
?>
  • I am suspicious. Why do you use both date_create and date_timestamp_set? – user4951 Nov 28 '13 at 06:57
  • 5
    $date = date_create(); Return a new DateTime object and date_timestamp_set(); Set the date and time based on a Unix timestamp –  Nov 28 '13 at 12:28
0

REQUEST_TIME - It is unix timestamp - The timestamp of the start of the request.

$dateStamp = $_SERVER['REQUEST_TIME'];
echo date('d m Y', $dateStamp);

OR

$date = new DateTime($dateStamp);
echo $date->format('Y-m-d');
Krish R
  • 22,583
  • 7
  • 50
  • 59
0

this code will work for you

$dateStamp = $_SERVER['REQUEST_TIME'];

echo date('d-M-Y H:i:s',strtotime($dateStamp));