0

I'm trying to convert a time format in the format below to a unix timestamp using PHP

j n Y H:i:s

Im trying to find a way to convert to a unix timestamp so it can be used in SQL databases. An example of the dates that I need to convert:

28 Mar 12 16:37:34

I've tried functions called "strptime" and "mktime" that I found on stackoverflow to no success - im not really sure what Im doing with them. If this is the answer here, could someone explain how to use them? Ive tried to understand the PHP documentation but Im just not getting it.

The post I was reading is here: PHP date format converting

Community
  • 1
  • 1
kirgy
  • 1,567
  • 6
  • 23
  • 39

3 Answers3

2

echo strtotime('28 Mar 12 16:37:34'); //1332945454

http://php.net/manual/en/function.strtotime.php

Lawrence Cherone
  • 46,049
  • 7
  • 62
  • 106
  • Thanks! I knew there had to be something simple I was missing :) – kirgy Mar 29 '12 at 00:10
  • 1
    @kirgy: Output value may be different than `1332945454` in this case. Timestamp depends of timezone setting and this code doesn't output same value for every timezone. Just be aware. Instead, set your timezone before you use `strtotime()` function (take a look of [date_default_timezone_set](http://php.net/manual/en/function.date-default-timezone-set.php)) or append timezone/offset to your string, something like `strtotime('28 Mar 12 16:37:34 UTC')`, `strtotime('28 Mar 12 16:37:34 PST')`, `strtotime('28 Mar 12 16:37:34 UTC+0200')`, etc. – Wh1T3h4Ck5 Mar 29 '12 at 00:41
  • thanks for that, I had written my own xml parser, then clipped off the timezone part, in my case {+0000} i was encountering problems when comparing it to current system time because it seemed to not take into account daylight saving without the timezone. Now with timezone including, it works as expected. – kirgy Mar 29 '12 at 01:09
2

If you need ultimate flexibility on parsing the format, use DateTime::createFromFormat()

$dt = DateTime::createFromFormat(
    'j M y H:i:s', $dateString, new DateTimeZone('Your/Timezone'));
$timestamp = $dt->getTimestamp();
Phil
  • 157,677
  • 23
  • 242
  • 245
0

The php way is to use date() and strtotime()

sql uses YYYY-MM-DD HH:MM:SS

$dateTime = date('Y-m-d H:i:s', strtotime('28 Mar 12 16:37:34'));
Yada
  • 30,349
  • 24
  • 103
  • 144
  • Function date() doesn't return timestamp. OP wants to convert formatted date/time string into Unix timestamp (read title & question), not to change formatted string from one to another. Your example returns `'2012-03-28 16:37:34'` which is also formatted string. – Wh1T3h4Ck5 Mar 29 '12 at 00:44