If you are a PHP programmer, you always find yourself converting date format to string from time to time. Here’s few examples on converting date to string format.

PHP Programming


< ?php
/*
@format
1 - January 1, 1970 12:00:00 AM/PM  # full date and 12 hour format (default)
2 - January 1, 1970 23:00:00   # full date and 24 hour format
3 - Jan 1, 1970 12:00:00 AM/PM  #short date and 12 hour format
4 - Jan 1, 1970 24:00:00 # short date and 24 hour format
*/

function convertDate2String($inputDate,$dateFormat=1) {

    switch ($dateFormat) {
       case 1:
            return date('F d, Y h:i:s A', strtotime($inputDate));
       break;

       case 2:
            return date('F d, Y G:i:s', strtotime($inputDate));
       break;

       case 3:
            return date('M d, Y h:i:s A', strtotime($inputDate));
       break;

       case 4:
            return date('M d, Y G:i:s', strtotime($inputDate));
       break;
    }
}

/* example usage */

print convertDate2String("2009-08-10 18:00:00"); //Outputs: August 10, 2009 06:00:00 PM

?>


You can play with the format and feel free to make variations of the code according to your requirements.

4 Comments

  1. gk says:

    Here we have convert String2Date… not Date2String…

  2. WL says:

    Great stuff!

  3. Tony says:

    How do you put this in spanish?

  4. German says:

    Thank you so much for this post!!!

Leave a Reply

Your email address will not be published. Required fields are marked *