4

I have a database that stores the time for me. I insert it from PHP using

date( 'Y-m-d H:i:s');

I then use this function to convert it to a unix timestamp in PHP

function convert_datetime($str) 
{
list($date, $time) = explode(' ', $str);
list($year, $month, $day) = explode('-', $date);
list($hour, $minute, $second) = explode(':', $time);

$timestamp = mktime($hour, $minute, $second, $month, $day, $year);

return $timestamp;
}

What I now need to do is convert this timestamp to the date and time in this format: yyyymmddhhmmss (without any hyphens, dashes, colons, etc).

Has anyone any ideas?

1
  • php.net/date has a complete list of date()'s formatting parameters Commented Sep 14, 2010 at 9:16

5 Answers 5

16

You can use the strtotime and date function:

echo date('Ymdhis', strtotime($date));
Sign up to request clarification or add additional context in comments.

Comments

11

Use date.

$date = date("YmdHis", $timestamp);

Comments

3

here you go

print date("YmdHis",unixtimestamp);

Comments

2

If you're using mysql, it has a DATE_FORMAT function. You can call it like

SELECT DATE_FORMAT(`datefield`, "%Y%m%d%H%i%s") AS `date_formatted` FROM table;

So you get an already formatted date from your database.

1 Comment

I would also recommend this approach rather than using PHP. I haven't done any benchmarks but I suspect it's orders of magnitude faster. Also, use NOW() in SQL, instead of date('Y-m-d H:i:s'); in PHP for the insertion, if you can.
1

Use the right format :

date('YmdHis');

Comments

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.