PHP Convert Date and Time to String

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.

Permalink • Print • Comment

Trackback uri

http://seoroot.com/blog/computing/programming/php-convert-date-and-time-to-string.html/trackback

Related Entries

4 Comments on PHP Convert Date and Time to String »

gk @ 10:18 am:

Here we have convert String2Date… not Date2String…

WL @ 4:27 am:

Great stuff!

Tony @ 2:41 pm:

How do you put this in spanish?

German @ 7:26 pm:

Thank you so much for this post!!!

Leave a Comment