Sunday, January 16, 2011

The best way to handle date and time in PHP and MySQL

Usually we use date() function with their different formats. When we have to store the date in table, we convert the date in yyyy-mm-dd format if data-type of column is Date or yyyy-mm-dd HH:mm:ss format if data-type of column is datetime . In the same way, before use of these values, after fetching, need to convert these according to our required format. But, doing all the above process, we have to use explode() and list() function many times. But, using strtotime() is the best way to handle date in different formats.
strtotime() is a function that converts a date which is in string format into unix timestamp. Please select the data-type as timestamp instead date or datetime when define table structure.
At the time of saving, we have to just pass the date value which is in string format as argument of strtotime() function and get  the timestamp as output of this function. Now, we can save this timestamp in the table.
At the time of using this value, after fetching pass this timestamp value in the date() function as second parameter. Format will be as below:
<?php 
//Before saving the value in table,
$timestamp_field_value=strtotime('2010-12-23 12:55:32');
//After fetching the value from table,
echo date('Y-m-d',$timestamp_field_value);
?>

No comments:

Post a Comment

Thanks for your valuable comments.

Important queries based formulas to watch performance of a MySQL based application

(1) Session Vs global status variables value select G.variable_name,G.variable_value GlobalValue,S.variable_value SessionValue from (selec...