0

Possible Duplicate:
How to convert date to timestamp in PHP?

I want to transfer some date to timestamp ,the date formart is %day %month %time. Like 25 nov 07:44, I tried some method below, but the two dates are different. need a help, thanks.

<?php
$date = '25 nov 07:44';
$time = explode(" ",$date);
$minute = explode(":",$time[2]);
$timestamp = mktime(''.$minute[0].' '.$minute[1].' 00 '.$time[1].' '.$time[0].' 2011')."<br />";// mktime(%hour, %minute, %second, %month, %day, %year);
echo $timestamp; //1322202671
echo date("Y-m-j H:i:s", $timestamp); //2011-11-25 07:31:11
?>
Community
  • 1
  • 1
fish man
  • 2,666
  • 21
  • 54
  • 94

2 Answers2

5

A few problems:

  • You are feeding mktime a string instead of a comma separated list
  • $time[1] is a string and mktime needs a number for the month

You might want to give it a try with strtotime or otherwise add a translation table to go from your month strings to a number.

jeroen
  • 91,079
  • 21
  • 114
  • 132
  • so what is the right `strtotime` formart for me? `"25-11-2011 07:44"`? so I shall make a str_replace for `nov` to `11`? Thanks. – fish man Nov 25 '11 at 22:48
  • 1
    @fish man see the manual for information about [`strtotime`](http://php.net/manual/en/function.strtotime.php) – Anonymous Nov 25 '11 at 22:56
  • Thanks for `strtotime`, `+1` ,but `DateTime::createFromFormat($format, $timestamp);` is a new way for me, a php starter, also not quite know the new method in `php5.3+` – fish man Nov 25 '11 at 22:58
  • 1
    @fish man I agree; unfortunately I'm limited to php5.2 for most of my projects... – jeroen Nov 25 '11 at 23:00
  • @jeroen, so do I, I updated my php version to new, but my text book is `php5.1`. – fish man Nov 25 '11 at 23:04
1

In recent versions of php (5.3+), you can use DateTime::createFromFormat().

Try something like

$format = 'd M H:i';
$date = DateTime::createFromFormat($format, $timestamp);
echo $date->format('Y-m-j H:i:s'); 

Personally, I find this class based approach a little cleaner.

PHP Docs:

DateTime::createFromFormat

date() for info on format strings

Adam
  • 5,091
  • 5
  • 32
  • 49