Skip to content

Instantly share code, notes, and snippets.

@nragaz
Created March 16, 2011 03:21
Show Gist options
  • Save nragaz/871957 to your computer and use it in GitHub Desktop.
Save nragaz/871957 to your computer and use it in GitHub Desktop.
Calculate M-F hours between 2 times in MySQL
@new := reports.downloaded_at,
@old := pages.created_at,
@oldWeek := WEEK(@old, 2),
@newWeek := WEEK(@new, 2),
@weekends := @newWeek - @oldWeek,
@weekendSecs := @weekends * 172800,
@oldWeekSaturday := STR_TO_DATE( CONCAT(DATE_FORMAT(@old, '%X%V'), ' Saturday'), '%X%V %W %h-%i-%s'),
@extraFirstWeekSecs := TIME_TO_SEC( TIMEDIFF(@old, @oldWeekSaturday) ),
@extraFirstWeekSecs := (@extraFirstWeekSecs > 0) * @extraFirstWeekSecs,
@newWeekSaturday := STR_TO_DATE( CONCAT(DATE_FORMAT(@new, '%X%V'), ' Saturday'), '%X%V %W %h-%i-%s'),
@extraLastWeekSecs := TIME_TO_SEC( TIMEDIFF(@new, @newWeekSaturday) ),
@extraLastWeekSecs := (@extraLastWeekSecs > 0) * @extraLastWeekSecs,
@totalSecs := TIME_TO_SEC( TIMEDIFF(@new, @old) ),
@totalHours := @totalSecs / 3600 as total_hours,
@avg := (@totalSecs - @weekendSecs + @extraFirstWeekSecs + @extraLastWeekSecs) / 3600 as weekday_hours
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment