Friday, 31 August 2007

Rounding datetime to midnight

SQL Server
select dateadd(dd,0, datediff(dd,0, datetimeval)) as date_at_midnight

MySql
SELECT DATE_FORMAT(now(), '%Y-%m-%d 00:00:00')

1 comment:

  1. I realize this is really old (in internet time) but you have no idea how much this little statement helped me today. I've been prowling the internet literally for hours trying find a simple way to get the first row in a table timestamped after midnight today (as in really early morning) and every single stinking answer I found was incredibly complex or just plain wrong. I took this simple rounding explanation and added it to a simple query and it worked the first time.

    Now I'm thinking about adding a comment to the hundred or so bad examples I tried to follow from various sources that didn't have any idea what they were talking about.

    Thank You

    ReplyDelete