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

3 Answers 3

2

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

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

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks! I knew there had to be something simple I was missing :)
@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) 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.
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.
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();

Comments

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'));

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.