有没有办法获得一个月的第一个和最后一个工作日? [英] Is there a way to get the First and Last weekday of a month?

查看:45
本文介绍了有没有办法获得一个月的第一个和最后一个工作日?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想问一下在 MySQL 中是否有一种智能或简单的方法来获取一个月的第一个和最后一个工作日.换句话说,我想避开周末并适当地调整第一天或最后一天.

I would like to ask if there is a smart or easy way to get the first and last weekday of a month in MySQL. In other way, I want to avoid Weekends and shift first or last day properly.

例如:

For the period: 2011-05-01 till 2011-05-31
First weekday should be: 2011-05-02 and not 2011-05-01 as 2011-05-01 is Sunday.
Last weekday should be: 2011-05-31 as it is Tuesday.

For the period: 2011-04-01 till 2011-04-30,
First weekday: 2011-04-01
Last weekday: 2011-04-29

推荐答案

如何定义函数FIRST_WDOM()(星期/一个月的工作日)和LAST_WDOM()LAST_DAY()?

How about defining functions FIRST_WDOM() (week/work day of month) and LAST_WDOM() in the style of LAST_DAY()?

DELIMITER //
CREATE FUNCTION first_wdom (d DATETIME) -- First work/week day of month
RETURNS DATE DETERMINISTIC
BEGIN
  DECLARE first_dom DATE;
  SET first_dom = DATE_FORMAT(d, '%Y-%m-01');

  RETURN first_dom + INTERVAL (CASE DAYOFWEEK(first_dom)
                               WHEN 1 THEN 1
                               WHEN 7 THEN 2
                               ELSE 0
                               END) DAY;
END //
CREATE FUNCTION last_wdom (d DATETIME) -- Last work/week day of month
RETURNS DATE DETERMINISTIC
BEGIN
  DECLARE last_dom DATE;
  SET last_dom = LAST_DAY(d);

  RETURN last_dom - INTERVAL (CASE DAYOFWEEK(last_dom)
                              WHEN 1 THEN 2
                              WHEN 7 THEN 1
                              ELSE 0
                              END) DAY;
END //
DELIMITER ;

mysql> SELECT FIRST_WDOM('2011-05-10'), LAST_WDOM('2011-05-10');
+--------------------------+-------------------------+
| FIRST_WDOM('2011-05-10') | LAST_WDOM('2011-05-10') |
+--------------------------+-------------------------+
| 2011-05-02               | 2011-05-31              | 
+--------------------------+-------------------------+
1 row in set (0.01 sec)

这仅仅是对ic3b3rg 的答案,并假设周六和周日是您的周末.我使用 DATETIME 而不是 DATE 作为输入类型,以避免在传入时出现截断警告,例如 NOW().

This is merely an adaptation of ic3b3rg's answer, and assumes that Saturday and Sunday are your weekend days. I use DATETIME, rather than DATE, as the input type to avoid truncation warnings when passing in, say, NOW().

这篇关于有没有办法获得一个月的第一个和最后一个工作日?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆