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.

Batman has written 223 articles

4 thoughts on “PHP Convert Date and Time to String

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">