21

I'm trying to get a unix timestamp with PHP but it doesn't seem to be working. Here is the format I'm trying to convert to a unix timestamp:

PHP

$datetime = '2012-07-25 14:35:08';

$unix_time = date('Ymdhis', strtotime($datetime ));
echo $unix_time;

My result looks like this:

20120725023508

Any idea what I'm doing wrong?

user1216398
  • 1,890
  • 13
  • 32
  • 40

3 Answers3

35

strtotime Returns a timestamp on success, FALSE otherwise.

 echo strtotime('2012-07-25 14:35:08' );

Output

1343219708
Baba
  • 94,024
  • 28
  • 166
  • 217
  • 1
    ahh..trying to make it harder then it needs to be. Thanks! – user1216398 Oct 09 '12 at 15:06
  • 2
    @Baba But strtotime is timezone specific, isn't it ? – shasi kanth Jul 22 '13 at 12:38
  • 1
    CAREFUL! `strtotime` assumes the time string is in the time zone specified by php's current `date_default_timezone_get`. If unsure, FIRST call `date_default_timezone_set` with the timezone name that corresponds to the source of your date strings. – ToolmakerSteve Aug 04 '16 at 17:28
3

This is converting it to a unix timestamp: strtotime($datetime), but you're converting it back to a date again with date().

Niklas Modess
  • 2,521
  • 1
  • 20
  • 34
3

To extend the answers here with an object-oriented solution, the DateTime class must be named. The DateTime class is available since PHP 5.2 and can be used as follows.

$date = DateTime::createFromFormat('Y-m-d H:i:s', '2012-07-25 14:35:08');
echo $date->getTimestamp(); // output: 1343219708

Or even as a one-liner

echo $date = (new DateTime('2012-07-25 14:35:08'))->getTimestamp();
// output: 1343219708
Marcel
  • 4,854
  • 1
  • 14
  • 24