Clear Time function for MySQL « Intelligrape Groovy & Grails Blogs

Clear Time function for MySQL

Posted by

Hi all,

Here is a simple function that can allow you to clear time from the DATETIME field of your database table

DROP FUNCTION IF EXISTS cleartime;
delimiter //
CREATE FUNCTION cleartime(dt datetime) RETURNS DATETIME
  NO SQL
  DETERMINISTIC
BEGIN
  DECLARE t    varchar(15);               -- the time part of the dt
  DECLARE rdt  datetime default dt;    	  -- the datetime after time part is cleared

  SET t = TIME(dt); 
  SET rdt = SUBTIME(dt,t);

  RETURN rdt;
END //
delimiter ;

To import this function to your database just copy and paste above code in MySQL command prompt with your database selected.

The implementation is shown in following example:

select cleartime(datetime_field) from table_name;     -- to view field with its time cleared
                     --OR
update table_name set datetime_field=cleartime(datetime_feild) from table_name;
This entry was posted on April 12th, 2012 at 12:06 pm and is filed under Database . You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

Leave a Reply