3

Possible Duplicate:
Convert one date format into another in PHP

I know there are plenty of posts out there, however there is not any validated or accepted answer that explains that well!

I'm working with Wordpress and use this to save a date into a database …

update_post_meta($post->ID, "event_date", $_POST["_wr_event_date"]);

I simply put in my desired date like 08.05.2012 into the _wr_event_date Field and it successfully gets stored into the database. However for further stuff I need this date to be sortable and I want to convert it into a unix timestamp.

How can I convert my entered date value "08.05.2012" (which is in german date format: %d.%m.%Y) to a unix timestamp that represents this time?

I thought of using pdate_post_meta($post->ID, "event_date", strtotime($_POST["_wr_event_date"])); but I wonder if this is the correct way because I can't think of a reason why strtotime() should automagically know what date format I've put in!?

Any thoughts on that? thank you in advance.

Community
  • 1
  • 1
matt
  • 42,713
  • 103
  • 264
  • 397
  • `strtotime(implode('-',array_reverse(explode('.', $_POST["_wr_event_date"])))` will give the correct timestamp. `nnnn-nn-nn` is always assumed to be `yyyy-mm-dd` by `strtotime()` – DaveRandom May 09 '12 at 08:45
  • just because there isnt (supposedly) any answers showing how to use [`DateTime::createFromFormat`](http://php.net/manual/en/datetime.createfromformat.php) with your specific format, doesnt mean the question hasnt been answered before. It's merely a matter of abstraction. A question is not not a duplicate because we simply didnt give any combination of possible arguments to it yet. – Gordon May 09 '12 at 08:45

2 Answers2

2

Just use DateTime (strtotime, works similar but I prefer DateTime):

$a = new DateTime('08.05.2012');
echo $a->getTimestamp();

strtotime and the DateTime library are very well written and they detect nearly every case, so you are good to go.

Otherwise, just pick a DATE field in your database, then you can sort it there too.

dan-lee
  • 14,365
  • 5
  • 52
  • 77
  • it seems I do not have the dateTime library installed? How can I do this? – matt May 09 '12 at 09:00
  • According to the [manual](http://de.php.net/manual/en/datetime.installation.php) your version is below PHP 5.2, because it says `There is no installation needed to use these functions; they are part of the PHP core.` So you should just stick to `strtotime()` it works similar accurate. (But if your version is really that old, you should consider upgrading it) – dan-lee May 09 '12 at 09:08
  • Ok, perfect thank you, I upgrade the php version and it worked! – matt May 09 '12 at 09:17
  • This works with this particular question, but it is highly unreliable in general. If you try d/m/Y: new DateTime('22/12/2009') - it will fail. There are plenty of countries with this date format. – Jeffz Feb 11 '19 at 03:21
0

You can also use the mktime function - mktime

Havelock
  • 6,913
  • 4
  • 34
  • 42