tags:

views:

131

answers:

5

Hi,

I am having a string as mentioned below:

$ts  = "3/11/09 11:18:59 AM"; which I have got using date() function

Now i need to convert this to a readable format like below

11-Mar-2009

I have ave tried everything using date()

Can someone please help me with this??

+3  A: 

You need to convert it to something you can use for further formatting. strtotime() is a good start, which yields a unix timestamp. You can format that one using strftime() then.

strftime("%d-%b-%G", strtotime($ts));
soulmerge
Thanks a ton.. It worked :)
gnanesh
strftime doesn't work under Windows
vava
True, It doesn't work on *every* installation - there are windows builds with this function, though. You can use date() instead, if you want to.
soulmerge
@Vadim: Which PHP for Windows installs doesn't it work under? strftime() is a wrapper over the C call of the same name, which is a standard part of time.h. As I recall, date() is also a wrapper over strftime(), but does more for you.
R. Bemrose
+1  A: 

If you initially get the string from the date() function, then pass on formatting arguments to the date-function instead:

date('Y-m-d')

instead of converting the string once again.

EDIT: If you need to keep track of the actual timestamp, then store it as a timestamp:

  
// Store the timestamp in a variable. This is just an integer, unix timestamp (seconds since epoch)
$time = time();

// output ISO8601 (maybe insert to database? whatever) 
echo date('Y-m-d H:i', $time);

// output your readable format
echo date('j-M-Y', $time);

Using strtotime() is convinient but unessecary parsing and storage of a timerepresentation is a stupid idea.

jishi
Thats not an option as I need to get the time as well.Only while I am displaying I need in the mentioned format
gnanesh
You should keep the date in an easily used format for the computer itself, not as a string. the return of the time() method is a good start, and then pass that variable as the 2nd argument to date() for formatting. I'll update my answer.
jishi
A: 

You can use the date() function to generate the required format directly, like so:

date("j-M-Y");

See www.php.net/date for all the possible formats of the output of the date() function.

Daan
Thats not an option as I need to get the time as well.Only while I am displaying I need in the mentioned format
gnanesh
+1  A: 

Actually I tried doing this and it worked.

echo date("d-M-Y", strtotime($ts));
gnanesh
I would recommend this over the current answer as it works in Windows as well.
St. John Johnson
A: 

JISHI's answer is correct

bluepicaso