Monday, April 25, 2011

date formatting in php

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??

From stackoverflow
  • 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));
    
    gnanesh : Thanks a ton.. It worked :)
    vava : strftime doesn't work under Windows
    soulmerge : 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.
    R. Bemrose : @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.
  • 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.

    gnanesh : Thats not an option as I need to get the time as well. Only while I am displaying I need in the mentioned format
    jishi : 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.
  • 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.

    gnanesh : Thats not an option as I need to get the time as well. Only while I am displaying I need in the mentioned format
  • Actually I tried doing this and it worked.

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

0 comments:

Post a Comment