Rounding Dates in MySQL 5

by timvasil 2/20/2008 12:19:00 AM

A while back I blogged about how to round dates in SQL Server 2000+.  Here's the MySQL port:

DROP FUNCTION IF EXISTS `dbname`.`fn_RoundDate` $$
CREATE FUNCTION `dbname`.`fn_RoundDate` (dateArg DATETIME, formatArg CHAR) RETURNS DATETIME
DETERMINISTIC
BEGIN

 IF dateArg IS NULL OR formatArg IS NULL THEN
    RETURN NULL;
  ELSEIF formatArg = 'T' THEN -- Time
    RETURN CAST(dateArg AS TIME);
  ELSE
    -- Round to day
    SET dateArg = CAST(dateArg AS DATE);

   RETURN CASE formatArg
    WHEN 'D' THEN -- Day
     CAST(dateArg AS DATE)
    WHEN 'W' THEN -- Week
        ADDDATE(dateArg, INTERVAL 1 - DAYOFWEEK(dateArg) DAY)
    WHEN 'M' THEN -- Month
        ADDDATE(dateArg, INTERVAL 1 - DAYOFMONTH(dateArg) DAY)
      WHEN 'Q' THEN -- Quarter
        ADDDATE(MAKEDATE(YEAR(dateArg), 1), INTERVAL FLOOR(MONTH(dateArg) / 4) QUARTER)
    WHEN 'Y' THEN -- Month
        ADDDATE(dateArg, INTERVAL 1 - DAYOFYEAR(dateArg) DAY)
    ELSE -- Unknown format
     dateArg
    END;
  END IF;

END $$

DELIMITER ;

Why there isn't a built-in function to do something so useful--in either SQL Server or MySQL--is beyond me.

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags:

MySQL

Related posts

Comments

Comments are closed

 

About the author

Tim Vasil Tim Vasil
I'm a software engineer living in Cambridge, MA.

E-mail me Send mail

Search

Calendar

<<  September 2010  >>
MoTuWeThFrSaSu
303112345
6789101112
13141516171819
20212223242526
27282930123
45678910

View posts in large calendar

Recent comments