在 MariaDB 中获取日期对应的星期几

本文讨论如何在 MariaDB 中使用 DATE_FORMAT() 函数获取指定的日期是星期几。

发布于

在 MariaDB 中,您可以使用 DATE_FORMAT() 函数返回日期对应的是星期几,可以是短名称(比如 TueWed),也可以是全名称(比如 TuesdayWednesday)。

获取短名称

在 MariaDB 中,您可以在 DATE_FORMAT() 函数中 %a 格式说明符获取指定日期的短名称,例如:

SELECT DATE_FORMAT('2022-12-12', '%a');

输出:

+---------------------------------+
| DATE_FORMAT('2022-12-12', '%a') |
+---------------------------------+
| Mon                             |
+---------------------------------+

获取长名称

在 MariaDB 中,您可以在 DATE_FORMAT() 函数中 %W 格式说明符获取指定日期的长名称,例如:

SELECT DATE_FORMAT('2022-12-12', '%W');

输出:

+---------------------------------+
| DATE_FORMAT('2022-12-12', '%W') |
+---------------------------------+
| Monday                          |
+---------------------------------+

获取当前日期的名称

下面的示例展示了如何获取当前日期是星期几:

SELECT
  CURRENT_DATE,
  DATE_FORMAT(CURRENT_DATE, '%W') "Full Name",
  DATE_FORMAT(CURRENT_DATE, '%a') "Short Name";

输出:

+--------------+-----------+------------+
| CURRENT_DATE | Full Name | Short Name |
+--------------+-----------+------------+
| 2022-12-12   | Monday    | Mon        |
+--------------+-----------+------------+

获取一周中所有的工作日名称

下面的示例展示了如何获取获取所有的工作日的名称,包括长名称和段名称:

SELECT
  '2022-12-12' AS "Day",
  DATE_FORMAT('2022-12-12', '%W') AS "Full Name",
  DATE_FORMAT('2022-12-12', '%a') AS "Short Name"
UNION
SELECT
  '2022-12-13' AS "Day",
  DATE_FORMAT('2022-12-13', '%W') AS "Full Name",
  DATE_FORMAT('2022-12-13', '%a') AS "Short Name"
UNION
SELECT
  '2022-12-14' AS "Day",
  DATE_FORMAT('2022-12-14', '%W') AS "Full Name",
  DATE_FORMAT('2022-12-14', '%a') AS "Short Name"
UNION
SELECT
  '2022-12-15' AS "Day",
  DATE_FORMAT('2022-12-15', '%W') AS "Full Name",
  DATE_FORMAT('2022-12-15', '%a') AS "Short Name"
UNION
SELECT
  '2022-12-16' AS "Day",
  DATE_FORMAT('2022-12-16', '%W') AS "Full Name",
  DATE_FORMAT('2022-12-16', '%a') AS "Short Name"
UNION
SELECT
  '2022-12-17' AS "Day",
  DATE_FORMAT('2022-12-17', '%W') AS "Full Name",
  DATE_FORMAT('2022-12-17', '%a') AS "Short Name"
UNION
SELECT
  '2022-12-18' AS "Day",
  DATE_FORMAT('2022-12-18', '%W') AS "Full Name",
  DATE_FORMAT('2022-12-18', '%a') AS "Short Name";

输出:

+------------+-----------+------------+
| Day        | Full Name | Short Name |
+------------+-----------+------------+
| 2022-12-12 | Monday    | Mon        |
| 2022-12-13 | Tuesday   | Tue        |
| 2022-12-14 | Wednesday | Wed        |
| 2022-12-15 | Thursday  | Thu        |
| 2022-12-16 | Friday    | Fri        |
| 2022-12-17 | Saturday  | Sat        |
| 2022-12-18 | Sunday    | Sun        |
+------------+-----------+------------+

结论

本文讨论如何在 MariaDB 中使用 DATE_FORMAT() 函数获取指定的日期是星期几:

  • %a 格式说明符获取指定日期的短名称
  • %W 格式说明符获取指定日期的长名称

您可以查看更多 MariaDB 日期格式化说明符