How to convert date to time and back

This tutorial show how to convert DATE to TIME and customize output

MySQL spits out date in YYYY-MM-DD format. The following code will show how we can customize the output.

First thing we need to do is to convert the DATE to TIME:

<?
//Im just starting with  a date
$my_date = '2004-01-12';

//First : Convert the date to time
$my_time = strtotime($my_date);
?>

Yes, I have used the strtotime() function to convert the string $my_date to TIME. The strtotime() function will take an English date format and convert it to a UNIX timestamp.

Now that we have the TIME in $my_time, we can change the date output format to almost anything by using the DATE () function.

The following code will take the TIME in $my_time and display the date in YYYY-MM-DD format. [ This was the original format, but we are going to check if it really works ]

<?
//To display it as Y-m-d
echo date('Y-m-d',$my_time);
//This will give you 2004-01-12  (same as original)
?>

Note that we have used the DATE() function to convert the time to date.

Now if you would like to view the output as DD-MM-YYYY, use the following code

<?
//To display day-month-year
echo date('d-m-Y',$my_time);
//This will give you  12-01-2004

//To display the day, month spelled-out and Year
echo date("d , F Y", $my_time);
// This will give you  12 , January 2004
?>

This short tutorial was aimed to convert date to time and back to date in different formats. More information on PHP functions can be found at http://www.php.net

Nathan Pakovskie is an esteemed senior developer and educator in the tech community, best known for his contributions to Geekpedia.com. With a passion for coding and a knack for simplifying complex tech concepts, Nathan has authored several popular tutorials on C# programming, ranging from basic operations to advanced coding techniques. His articles, often characterized by clarity and precision, serve as invaluable resources for both novice and experienced programmers. Beyond his technical expertise, Nathan is an advocate for continuous learning and enjoys exploring emerging technologies in AI and software development. When he’s not coding or writing, Nathan engages in mentoring upcoming developers, emphasizing the importance of both technical skills and creative problem-solving in the ever-evolving world of technology. Specialties: C# Programming, Technical Writing, Software Development, AI Technologies, Educational Outreach

Leave a Reply

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

Back To Top