Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple PHP time format not working!

Tags:

date

php

I have the following value:

30/05/2010 @ 09:15:15

I need to convert it to Y-m-d H:i:s.

I've tried:

$date = "30/05/2010 @ 09:15:15";
$formatteddate = date("Y-m-d H:i:s", time($date));
echo $formatteddate;

I end up with a value dated 1970. I've also tried strtotime.

Can anyone point out what I'm missing?

like image 827
Dominor Novus Avatar asked May 13 '11 03:05

Dominor Novus


People also ask

How to display time PHP?

If you want to show date and time as per user's timezone, you can set the timezone manually using the date_default_timezone_set() function before the date() function call.

How to get current time in 12 hour format in PHP?

Current Date and Time <? php //current Date, i.e. 2013-08-01 echo date("Y-m-d"); //current Time in 12 hour format, i.e. 08:50:55pm echo date("h:i:sa"); //current Time in 24 hour format, i.e. 18:00:23 echo date("H:i:s"); //current Month, i.e. 08 echo date("m"); //current Month name, i.e. Aug echo date("M"); ?>

What does time () do in PHP?

The time() function returns the current time in the number of seconds since the Unix Epoch (January 1 1970 00:00:00 GMT).


2 Answers

The time() function does not have any parameters which is why it is going to give you an error.

I have tried to use strtotime() thinking that may work, but it is not. I will update my answer when I find something that works. However, first thing is that time() will not work.

Edit: As Phil just beat me to seconds before:

$date = str_replace("@ ", "", "30/05/2010 @ 09:15:15");
$date = str_replace("/", "-", $date);
$formatteddate = date("Y-m-d H:i:s", strtotime($date));
echo $formatteddate;

Example is here: http://codepad.org/heph1PG0

like image 160
Flipper Avatar answered Sep 21 '22 18:09

Flipper


If you're using PHP 5.3, try DateTime::createFromFormat(), eg

$dt = DateTime::createFromFormat('d/m/Y @ H:i:s', $date);

If not, strtotime() may work but you'll need to get rid of the @ symbol and change the forward slashes to hyphens (if that's an EU / AU date), eg

$time = strtotime(str_replace(array('@', '/'), array('', '-'), $date));

Edit:

To display the dates in the format you want, use

echo $dt->format('Y-m-d H:i:s'); // for DateTime
echo date('Y-m-d H:i:s', $time); // for strtotime
like image 42
Phil Avatar answered Sep 18 '22 18:09

Phil