Merge branch 'LCTT:master' into 20230501

This commit is contained in:
Hans zhao 2023-05-02 17:38:37 +08:00 committed by GitHub
commit b5911afb27
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
5 changed files with 459 additions and 244 deletions

View File

@ -0,0 +1,236 @@
[#]: subject: "Improve your coding skills with temporal values in MySQL"
[#]: via: "https://opensource.com/article/23/2/temporal-values-mysql"
[#]: author: "Hunter Coleman https://opensource.com/users/hunterc"
[#]: collector: "lkxed"
[#]: translator: "hanszhao80"
[#]: reviewer: "wxy"
[#]: publisher: "wxy"
[#]: url: "https://linux.cn/article-15774-1.html"
在 MySQL 中处理时间
======
![][0]
> 这篇关于 MySQL 中日期和时间的概述将帮助你在数据库表中处理时间值。
流行数据库系统 MySQL 的新老用户常常会对数据库处理时间值的方式感到困惑。有时用户不会费心去了解时间值的数据类型。这可能是因为他们觉得本身也没有什么好了解的。日期就是日期,对吧?好吧,并非总是如此。花几分钟时间了解 MySQL 如何存储和显示日期和时间是有益的。学习如何最好地利用数据库表中的时间值可以帮助你成为更好的编码者。
### MySQL 时间值类型
当你在 MySQL 中新建表时,选择合适的数据类型(`INT`、`FLOAT`、`CHAR` 等高效地保存插入到表中的数据。MySQL 为时间值提供了五种数据类型。它们是 `DATE`、`TIME`、`DATETIME`、`TIMESTAMP` 和 `YEAR`
MySQL 使用 `ISO 8601` 格式来存储以下格式的值LCTT 译注:国际标准 ISO 8601是国际标准化组织的日期和时间的表示方法全称为《数据存储和交换形式·信息交换·日期和时间的表示方法》
- `DATE``YYYY-MM-DD`
- `TIME``HH:MM:SS`
- `TIMESTAMP``YYYY-MM-DD HH:MM:SS`
- `YEAR``YYYY`
### DATETIME 与 TIMESTAMP 的比较
你可能已经注意到 <ruby>日期时间<rt>DATETIME</rt></ruby><ruby>时间戳<rt>TIMESTAMP</rt></ruby> 数据类型存有相同的数据。你可能想知道这两者之间是否有差异。答案是:有。
首先,可以使用的日期范围不同。`DATETIME` 可以保存 1000-01-01 00:00:00 和 9999-12-31 23:59:59 之间的日期,而 `TIMESTAMP` 的范围更有限,从 1970-01-01 00:00:01 到 2038-01-19 03:14:07 UTC。
其次,虽然两种数据类型都允许你 <ruby>自动初始化<rt>auto_initialize</rt></ruby><ruby>自动更新<rt>auto_update</rt></ruby> 它们各自的值(分别用 `DEFAULT CURRENT_TIMESTAMP``ON UPDATE CURRENT_TIMESTAMP`),但在 5.6.5 版本之前,对 `DATETIME` 值不能这样操作。如果你要用 `DATETIME`,你可以使用 `CURRENT_TIMESTAMP` 的 MySQL 同义词之一,例如 `NOW()``LOCALTIME()`
如果你对一个 `DATETIME` 值使用 `ON UPDATE CURENT_TIMESTAMP`(或其同义词之一),但没有使用 `DEFAULT CURRENT_TIMESTAMP` 子句,那么这个列的默认值为 `NULL`。除非你在表的定义中包含 `NOT NULL`,在这种情况下,它默认为 0。
另一件需要记住的重要事情是,尽管通常情况下,除非你声明一个默认值,否则 `DATETIME``TIMESTAMP` 列都没有一个默认值,但这个规则有一个例外。如果没有指定 `DEFAULT CURRENT_TIMESTAMP``ON UPDATE CURRENT_TIMESTAMP` 这两个子句,并且禁用 `explicit_defaults_for_timestamp` 这个变量,那么你表中的第一个 `TIMESTAMP` 列将被隐式创建。
要检查这个变量的状态,请运行:
```
mysql> show variables like 'explicit_default%';
```
如果你想打开或关闭它,运行这段代码(用 0 表示关闭,用 1 表示打开):
```
mysql> set explicit_defaults_for_timestamp = 0;
```
### TIME
MySQL 的 <ruby>时间<rt>TIME</rt></ruby> 数据类型可能看起来很简单,但有几件事是一个优秀的程序员应该牢记的。
首先要注意的是,虽然 `TIME` 经常被认为是一天中的时间,但它实际上是经过的时间。换句话说,它可以是一个负值,或者可以大于 23:59:59。在 MySQL 中,一个 `TIME` 值的范围可以是 -838:59:59 到 838:59:59。
另外如果你缩写一个时间值MySQL 会因你是否使用冒号作出不同解释。例如10:34 这个值被 MySQL 看作是 10:34:00。也就是说十点过后的 34 分钟。但是,如果你不使用冒号写作 `1034`MySQL 将其视为 00:10:34意思是 10 分钟 34 秒。
最后,你应该知道 `TIME` 值(以及 `DATETIME``TIMESTAMP` 字段的时间部分)从 5.6.4 版本开始,可以取一个小数部分。要使用它,请在数据类型定义的结尾处添加一个整数(最大值为 6的圆括号。
```
time_column TIME(2)
```
### 时区
时区变化不仅在现实世界中产生混乱和疲劳,而且也会在数据库系统中制造麻烦。地球被划分为 24 个独立的时区,通常每隔 15 度经度就会发生变化。我说通常是因为一些国家行事方式不同。例如中国只在一个时区运作,而不是预期的五个时区。
你如何处理处于不同时区的数据库系统的用户就成了一个问题。幸运的是MySQL 并没有使这个问题变得太困难。
要检查你的会话时区,请运行:
```
mysql> select @@session.time_zone;
```
如果结果显示 `System`,这意味着它正在使用你的 `my.cnf` 配置文件中设置的时区。如果你在本地计算机上运行你的 MySQL 服务器,这可能就是你会得到的,你不需要做任何改变。
如果你想改变你的会话的时区,请运行如下命令:
```
mysql> set time_zone = '-05:00';
```
这将你的时区设置为 <ruby>美国/东部<rt>US/Eastern</rt></ruby>,比 <ruby>协调世界时<rt>UTC</rt></ruby> 晚五个小时。
### 获得一周的日期
为了跟上本教程后面部分的代码,你应该在你的系统中创建一个带有日期值类型的表。比如:
```
mysql> create table test
( row_id smallint not null auto_increment primary key,
the_date date not null);
```
然后使用 ISO 8601 格式在表中插入一些随机日期,如
```
mysql> insert into test (the_date) VALUES ('2022-01-05');
```
我在我的 `test` 表中插入了四行日期值,你插入多少行都可以。
有时你可能想知道某一天是星期几。MySQL 给了你几种实现方法。
第一种,也是最显而易见的方法,是使用 `DAYNAME()` 函数。如下示例表所展示,`DAYNAME()` 函数可以告诉你每个日期是星期几:
```
mysql> SELECT the_date, DAYNAME(the_date) FROM test;
+------------+-------------------------------+
| the_date | DAYNAME(the_date) |
+------------+-------------------------------+
| 2021-11-02 | Tuesday |
| 2022-01-05 | Wednesday |
| 2022-05-03 | Tuesday |
| 2023-01-13 | Friday |
+------------+-------------------------------+
4 rows in set (0.00 sec)
```
另外两种获取星期几的方法是返回整数值,而不是星期几的名称,分别是 `WEEKDAY()``DAYOFWEEK()`。他们都返回数字,却又各不相同。`WEEKDAY()` 函数返回从 0 到 6 的数字,其中 0 代表星期一6 代表星期日。而 `DAYOFWEEK()` 则返回从 1 到 7 的数字,其中 1 代表星期日7 代表星期六。
```
mysql> SELECT the_date, DAYNAME(the_date),
WEEKDAY(the_date), DAYOFWEEK(the_date) FROM test;
+------------+------------------+------------------+--------------------+
| the_date | DAYNAME(the_date)| WEEKDAY(the_date)| DAYOFWEEK(the_date)|
| 2021-11-02 | Tuesday | 1 | 3 |
| 2022-01-05 | Wednesday | 2 | 4 |
| 2022-05-03 | Tuesday | 1 | 3 |
| 2023-01-13 | Friday | 4 | 6 |
+------------+------------------+------------------+--------------------+
4 rows in set (0.00 sec)
```
### 当你只想获取日期的一部分时
有时你可能在 MySQL 表中存储了一个日期,但是你只想获取日期的一部分。这并不是问题。
MySQL 中有几个顾名思义的函数,可以轻松获取日期对象的特定部分。以下是一些示例:
```
mysql> SELECT the_date, YEAR(the_date), MONTHNAME(the_date), 
DAYOFMONTH(the_date) FROM test ;
+-----------+---------------+-------------------+---------------------+
| the_date | YEAR(the_date)|MONTHNAME(the_date)| DAYOFMONTH(the_date)|
+-----------+---------------+-------------------+---------------------+
| 2021-11-02| 2021 | November | 2 |
| 2022-01-05| 2022 | January | 5 |
| 2022-05-03| 2022 | May | 3 |
| 2023-01-13| 2023 | January | 13 |
+-----------+---------------+-------------------+---------------------+
4 rows in set (0.00 sec)
```
MySQL 也允许你使用 `EXTRACT()` 函数来获取日期的一部分。你提供给函数的参数是一个单位说明符(确保是单数形式)、`FROM` 和列名。因此,为了从我们的 test 表中仅获取年份,你可以写:
```
mysql> SELECT EXTRACT(YEAR FROM the_date) FROM test;
+----------------------------------------------+
| EXTRACT(YEAR FROM the_date) |
+----------------------------------------------+
| 2021 |
| 2022 |
| 2022 |
| 2023 |
+----------------------------------------------+
4 rows in set (0.01 sec)
```
### 插入和读取不同格式的日期
正如之前提到的MySQL 使用 `ISO 8601` 格式存储日期和时间值。但是如果你想以另一种方式存储日期和时间值,例如 `MM-DD-YYYY` 格式怎么办首先不要尝试这样做。MySQL 以 8601 格式存储日期和时间,就是这样。不要尝试更改它。但是,这并不意味着你必须在将数据输入到数据库之前将数据转换为特定的格式,或者你不能以任何你想要的格式展示数据。
如果你想要将非 ISO 的格式的日期输入到表中,你可以使用 `STR_TO_DATE()` 函数。第一个参数是你想要存储在数据库中的日期的字符串值。第二个参数是格式化字符串,它让 MySQL 知道日期的组织方式。让我们看一个简单的例子,然后我将更深入地研究这个看起来很奇怪的格式化字符串是什么。
```
mysql> insert into test (the_date) values (str_to_date('January 13, 2023','%M %d, %Y'));
Query OK, 1 row affected (0.00 sec)
```
你将格式化字符串放在引号中,并在每个特殊字符前加上百分号。上面代码中的格式序列告诉 MySQL 我的日期由一个完整的月份名称 `%M`,后跟一个两位数的日期`%d`,然后是一个逗号,最后由一个四位数的年份 `%Y` 组成。请注意,大写很重要。
一些其他常用的格式化字符串字符是:
- `%b` 缩写月份的名称(例如: `Jan`
- `%c` 数字月份(例如: 1
- `%W` 星期名称(例如: `Saturday
- `%a` 星期名称的缩写(例如: `Sat`
- `%T` 24 小时制的时间(例如: `22:01:22`
- `%r` 带 AM/PM 的 12 小时制的时间(例如: `10:01:22 PM`
- `%y` 两位数的年份(例如: 23
请注意,对于两位数年份 `%y`,年份范围是 1970 到 2069。因此从 70 到 99 的数字被假定为 20 世纪,而从 00 到 69 的数字被假定为 21 世纪。
如果你有一个日期存储在你的数据库中,你想用不同的格式显示它,你可以使用这个 `DATE_FORMAT()` 函数:
```
mysql> SELECT DATE_FORMAT(the_date, '%W, %b. %d, %y') FROM test;
+-----------------------------------------+
| DATE_FORMAT(the_date, '%W, %b. %d, %y') |
+-----------------------------------------+
| Tuesday, Nov. 02, 21 |
| Wednesday, Jan. 05, 22 |
| Tuesday, May. 03, 22 |
| Friday, Jan. 13, 23 |
+-----------------------------------------+
4 rows in set (0.00 sec)
```
### 总结
本教程应该为你提供了一个关于 MySQL 中的日期和时间值的有用的概述。我希望本文教会了您一些新知识,使您能够更好地控制和理解 MySQL 数据库如何处理时间值。
*题图MJ/76b6481a-a271-4e81-bc17-dd7fbe08a240*
--------------------------------------------------------------------------------
via: https://opensource.com/article/23/2/temporal-values-mysql
作者:[Hunter Coleman][a]
选题:[lkxed][b]
译者:[hanszhao80](https://github.com/hanszhao80)
校对:[wxy](https://github.com/wxy)
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
[a]: https://opensource.com/users/hunterc
[b]: https://github.com/lkxed/
[1]: https://opensource.com/downloads/mariadb-mysql-cheat-sheet
[0]: https://img.linux.net.cn/data/attachment/album/202305/02/170932wivx7l84red2dvip.png

View File

@ -3,24 +3,26 @@
[#]: author: "arindam https://debugpointnews.com/author/dpicubegmail-com/"
[#]: collector: "lkxed"
[#]: translator: "geekpi"
[#]: reviewer: " "
[#]: publisher: " "
[#]: url: " "
[#]: reviewer: "wxy"
[#]: publisher: "wxy"
[#]: url: "https://linux.cn/article-15773-1.html"
KDE 团队开发新的电子书管理应用Arianna
KDE 团队正在开发新的电子书管理应用Arianna
======
**KDE 引入了 Arianna这是一款基于 Qt 和 Kirigami 构建的新 ePub 阅读器应用,集成了 Baloo可轻松组织和浏览文件。**
![][0]
> KDE 引入了 Arianna这是一款基于 Qt 和 Kirigami 构建的新 ePub 阅读器应用,集成了 Baloo可轻松组织和浏览文件。
著名的国际自由软件社区 KDE 正在开发新的 ePub 阅读器应用 Arianna。该应用程序建立在 Qt 和 Kirigami 之上,提供时尚现代的用户界面。
Arianna 同时充当 ePub 查看器和库管理应用。该应用利用 KDE 的文件索引和搜索框架 Baloo 来查找和分类用户设备上的现有 ePub 文件。
Arianna 既是 ePub 查看器,也是库管理应用。该应用利用 KDE 的文件索引和搜索框架 Baloo 来查找和分类用户设备上的现有 ePub 文件。
Arianna 的库视图会跟踪用户的阅读进度并在新书下载后立即更新。对于那些拥有较大库的人Arianna 提供内部搜索功能以及按流派、出版商或作者浏览书籍的能力。
Arianna 的库视图会跟踪用户的阅读进度并在新书下载后立即更新。对于那些拥有较大库的人Arianna 提供内部搜索功能以及按体裁、出版商或作者浏览书籍的能力。
Arianna 的实际阅读界面很简单,唯一的目的就是展示书的内容。但是,该应用确实有有用的功能,例如用于跟踪用户阅读进度的进度条和键盘导航功能。它还允许用户在书中搜索特定单词。
以下是公告的一些截图。
以下是来自公告的一些截图:
![Arianna - 主视图][1]
@ -34,11 +36,13 @@ Arianna 的实际阅读界面很简单,唯一的目的就是展示书的内容
flatpak install flathub org.kde.arianna
```
尽管它具有令人印象深刻的功能,但人们可能会质疑是否需要另一个 ePub 管理应用,因为已经有了 [Calibre][5],这是一个免费的开源替代方案。然而Arianna 现代而直观的设计,以及与 KDE 生态系统的无缝集成,使其成为 ePub 阅读器领域的有力竞争者。
尽管它具有令人印象深刻的功能,但人们可能会质疑是否需要另一个 ePub 管理应用,因为已经有了 [Calibre][5],这是一个自由开源的替代方案。然而Arianna 现代而直观的设计,以及与 KDE 生态系统的无缝集成,使其成为 ePub 阅读器领域的有力竞争者。
总之Arianna 是 KDE 大量应用中令人兴奋的新成员。它提供时尚现代的设计以及用于管理和阅读 ePub 文件的实用功能。随着它的不断发展,用户可以期待在未来有更多的改进和增强。
来自 [Carl 的博客][7]
> 来自 [Carl 的博客][7]
*题图MJ/665fb955-deb5-4519-9259-afa983b616cc*
--------------------------------------------------------------------------------
@ -47,7 +51,7 @@ via: https://debugpointnews.com/kde-app-arinna/
作者:[arindam][a]
选题:[lkxed][b]
译者:[geekpi](https://github.com/geekpi)
校对:[校对者ID](https://github.com/校对者ID)
校对:[wxy](https://github.com/wxy)
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
@ -58,4 +62,5 @@ via: https://debugpointnews.com/kde-app-arinna/
[3]: https://debugpointnews.com/wp-content/uploads/2023/04/Author-View.jpg
[4]: https://www.debugpoint.com/how-to-install-flatpak-apps-ubuntu-linux/
[5]: https://calibre-ebook.com/
[7]: https://carlschwan.eu/2023/04/13/announcing-arianna-1.0/
[7]: https://carlschwan.eu/2023/04/13/announcing-arianna-1.0/
[0]: https://img.linux.net.cn/data/attachment/album/202305/02/144229yuyuecfuueeujue6.png

View File

@ -2,7 +2,7 @@
[#]: via: "https://news.itsfoss.com/opera-one-browser/"
[#]: author: "Sourav Rudra https://news.itsfoss.com/author/sourav/"
[#]: collector: "lkxed"
[#]: translator: " "
[#]: translator: "XiaotingHuang22"
[#]: reviewer: " "
[#]: publisher: " "
[#]: url: " "
@ -74,7 +74,7 @@ via: https://news.itsfoss.com/opera-one-browser/
作者:[Sourav Rudra][a]
选题:[lkxed][b]
译者:[译者ID](https://github.com/译者ID)
译者:[XiaotingHuang22](https://github.com/XiaotingHuang22)
校对:[校对者ID](https://github.com/校对者ID)
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
@ -89,4 +89,4 @@ via: https://news.itsfoss.com/opera-one-browser/
[6]: https://news.itsfoss.com/content/images/2023/04/Opera-One_2.jpg
[7]: https://blogs.opera.com/news/2023/04/opera-one-developer/?ref=news.itsfoss.com
[8]: https://www.opera.com/one?ref=news.itsfoss.com
[9]: https://news.itsfoss.com/vivaldi-6-0/
[9]: https://news.itsfoss.com/vivaldi-6-0/

View File

@ -1,229 +0,0 @@
[#]: subject: "Improve your coding skills with temporal values in MySQL"
[#]: via: "https://opensource.com/article/23/2/temporal-values-mysql"
[#]: author: "Hunter Coleman https://opensource.com/users/hunterc"
[#]: collector: "lkxed"
[#]: translator: "hanszhao80"
[#]: reviewer: " "
[#]: publisher: " "
[#]: url: " "
Improve your coding skills with temporal values in MySQL
======
Both new and experienced users of the popular MySQL database system can often get confused about how temporal values are handled by the database. Sometimes users don't bother learning much about temporal value data types. This may be because they think there isn't much to know about them. A date is a date, right? Well, not always. Taking a few minutes to learn how MySQL stores and displays dates and times is beneficial. Learning how to best take advantage of the temporal values in your database tables can help make you a better coder.
### MySQL temporal data types
When you are building your tables in MySQL, you choose the proper data type which most efficiently holds the data you intend to insert into the table (`INT`, `FLOAT`, `CHAR`,and so on). MySQL provides you with five data types for temporal values. They are: `DATE`, `TIME`, `DATETIME`, `TIMESTAMP`, and `YEAR`.
MySQL uses the `ISO 8601` format to store the values in the following formats:
- **DATE**  YYYY-MM-DD
- **TIME**   HH:MM:SS
- **TIMESTAMP** YYYY-MM-DD  HH:MM:SS
- **YEAR** YYYY
### Datetime compared to Timestamp
You may have noticed that the `DATETIME` and `TIMESTAMP` data types hold the same data. You might wonder if there are any differences between the two. There are differences.
First, the range of dates that can be used differ. `DATETIME` can hold dates between 1000-01-01 00:00:00 and 9999-12-31 23:59:59, whereas `TIMESTAMP` has a much more limited range of 1970-01-01 00:00:01 to 2038-01-19 03:14:07 UTC.
Second, while both data types allow you to `auto_initialize` or `auto_update` their respective values (with `DEFAULT CURRENT_TIMESTAMP` and `ON UPDATE CURRENT_TIMESTAMP` respectively), doing so was not available for `DATETIME` values until version 5.6.5. You can use one of the MySQL synonyms for `CURRENT_TIMESTAMP` if you choose, such as `NOW()` or `LOCALTIME()`.
If you use `ON UPDATE CURENT_TIMESTAMP` (or one of its synonyms) for a `DATETIME` value, but do not use the `DEFAULT CURRENT_TIMESTAMP` clause, then the column will default to `NULL`. This happens unless you include `NOT NULL` in the table definition, in which case it defaults to zero.
Another important thing to keep in mind is that although normally neither a `DATETIME` nor a `TIMESTAMP` column have a default value unless you declare one, there is one exception to this rule. The first `TIMESTAMP` column in your table is implicitly created with both `DEFAULT CURRENT_TIMESTAMP` and `ON UPDATE CURRENT_TIMESTAMP` clauses if neither is specified and if the variable `explicit_defaults_for_timestamp` is disabled.
To check this variable's status, run:
```
mysql> show variables like 'explicit_default%';
```
If you want to turn it on or off, run this code, using 0 for off and 1 for on:
```
mysql> set explicit_defaults_for_timestamp = 0;
```
### Time
MySQL's `TIME` data type may seem simple enough, but there are a few things that a good programmer should keep in mind.
First, be aware that although time is often thought of as the time of day, it is in fact elapsed time. In other words, it can be a negative value or can be greater than 23:59:59. A `TIME` value in MySQL can be in the range of -838:59:59 to 838:59:59.
Also, if you abbreviate a time value, MySQL interprets it differently depending on whether you use a colon. For example, the value 10:34 is seen by MySQL as 10:34:00. That is, 34 minutes past ten o'clock. But if you leave out the colon, 1034', MySQL sees that as 00:10:34. That is, ten minutes and 34 seconds.
Finally, you should know that `TIME` values (as well as the time portion of `DATETIME` and `TIMESTAMP` columns) can, as of version 5.6.4, take a fractional unit. To use it, add an integer (max value six) in parentheses at the end of the data type definition.
```
time_column TIME(2)
```
### Time zones
Time zone changes not only cause confusion and fatigue in the real world, but have also been known to cause problems in database systems. The earth is divided into 24 separate time zones which usually change with every 15 degrees of longitude. I say usually because some nations choose to do things differently. China, for example, operates under a single time zone instead of the five that would be expected.
The question is, how do you handle users of a database system who are in different time zones. Fortunately, MySQL doesn't make this too difficult.
To check your session time zone, run:
```
mysql> select @@session.time_zone;
```
If it says `System`, that means that it is using the timezone set in your `my.cnf`configuration file. If you are running your MsSQL server on your local computer, this is probably what you'll get, and you don't need to make any changes.
If you would like to change your session's time zone, run a command such as:
```
mysql> set time_zone = '-05:00';
```
This sets your time zone to five hours behind UTC. (US/Eastern).
### Getting the day of the week
To follow along with the code in the rest of this tutorial, you should create a table with date values on your system. For example:
```
mysql> create table test
( row_id smallint not null auto_increment primary key,
the_date date not null);
```
Then insert some random dates into the table using the ISO 8601 format, such as:
```
mysql> insert into test (the_date) VALUES ('2022-01-05');
```
I put four rows of date values in my test table, but put as few or as many as you'd like.
Sometimes you may wish to know what day of the week a particular day happened to be. MySQL gives you a few options.
The first, and perhaps most obvious way, is to use the `DAYNAME()` function. Using the example table, `DAYNAME()` tells you the day of the week for each of the dates:
```
mysql> SELECT the_date, DAYNAME(the_date) FROM test ;
+------------+-------------------------------+
| the_date | DAYNAME(the_date) |
+------------+-------------------------------+
| 2021-11-02 | Tuesday |
| 2022-01-05 | Wednesday |
| 2022-05-03 | Tuesday |
| 2023-01-13 | Friday |
+------------+-------------------------------+
4 rows in set (0.00 sec)
```
The other two methods for getting the day of the week return integer values instead of the name of the day. They are `WEEKDAY()`and `DAYOFWEEK()`. They both return numbers, but they do not return the same number. The `WEEKDAY()` function returns a number from 0 to 6, with 0 being Monday and 6 being Sunday. On the other hand, `DAYOFWEEK()` returns a number from 1 to 7, with 1 being Sunday and 7 being Saturday.
```
mysql> SELECT the_date, DAYNAME(the_date),
WEEKDAY(the_date), DAYOFWEEK(the_date) FROM test;
+------------+------------------+------------------+--------------------+
| the_date | DAYNAME(the_date)| WEEKDAY(the_date)| DAYOFWEEK(the_date)|
| 2021-11-02 | Tuesday | 1 | 3 |
| 2022-01-05 | Wednesday | 2 | 4 |
| 2022-05-03 | Tuesday | 1 | 3 |
| 2023-01-13 | Friday | 4 | 6 |
+------------+------------------+------------------+--------------------+
4 rows in set (0.00 sec)
```
### When you only want part of the date
Sometimes you may have a date stored in your MySQL table, but you only wish to access a portion of the date. This is no problem.
There are several conveniently-named functions in MySQL that allow for easy access to a particular portion of a date object. To show just a few examples:
```
mysql> SELECT the_date, YEAR(the_date), MONTHNAME(the_date), 
DAYOFMONTH(the_date) FROM test ;
+-----------+---------------+-------------------+---------------------+
| the_date | YEAR(the_date)|MONTHNAME(the_date)| DAYOFMONTH(the_date)|
+-----------+---------------+-------------------+---------------------+
| 2021-11-02| 2021 | November | 2 |
| 2022-01-05| 2022 | January | 5 |
| 2022-05-03| 2022 | May | 3 |
| 2023-01-13| 2023 | January | 13 |
+-----------+---------------+-------------------+---------------------+
4 rows in set (0.00 sec)
```
MySQL also allows you to use the `EXTRACT() function` to access a portion of a date. The arguments you provide to the function are a unit specifier (be sure that it's singular), `FROM`, and the column name. So, to get just the year from our test table, you could write:
```
mysql> SELECT EXTRACT(YEAR FROM the_date) FROM test;
+----------------------------------------------+
| EXTRACT(YEAR FROM the_date) |
+----------------------------------------------+
| 2021 |
| 2022 |
| 2022 |
| 2023 |
+----------------------------------------------+
4 rows in set (0.01 sec)
```
### Inserting and reading dates with different formats
As mentioned earlier, MySQL stores date and time values using the `ISO 8601` format. But what if you want to store date and time values another way, such as MM-DD-YYYY for dates? Well, first off, don't try. MySQL stores dates and times in the `8601 format` and that's the way it is. Don't try to change that. However, that doesn't mean you have to convert your data to that particular format before you enter it into your database, or that you cannot display the data in whatever format you desire.
If you would like to enter a date into your table that is formatted in a non-ISO way, you can use `STR_TO_DATE()`. The first argument is the string value of the date you want to store in your database. The second argument is the formatting string which lets MySQL know how the date is organized. Let's look at a quick example, and then I'll delve a little deeper into what that odd-looking formatting string is all about.
```
mysql> insert into test (the_date) values (str_to_date('January 13, 2023','%M %d, %Y'));
Query OK, 1 row affected (0.00 sec)
```
You put the formatting string in quotes, and precede each of the special characters with a percent sign. The format sequence in the above code tells MySQL that my date consists of a full month name `(%M)`, followed by a two-digit day `(%d)`, then a comma, and finally a four-digit year `(%Y)`. Note that capitalization matters.
Some of the other commonly used formatting string characters are:
- `%b` abbreviated month name (example: Jan)
- `%c` numeric month (example: 1)
- `%W` name of day (example: Saturday)
- `%a` abbreviated name of day (example: Sat)
- `%T` 24-hour time (example: 22:01:22)
- `%r` 12-hour time with AM/PM (example: 10:01:22 PM)
- `%y` 2-digit year (example: 23)
Note that for the 2-digit year (`%y`) the range of years is 1970 to 2069. So numbers from 70 through 99 are assumed 20th century, while numbers from 00 to 69 are assumed to be 21st century.
If you have a date stored in your database, and you would like to display it using a different format, you can use the `DATE_FORMAT()` function:
```
mysql> SELECT DATE_FORMAT(the_date, '%W, %b. %d, %y') FROM test;
+-----------------------------------------+
| DATE_FORMAT(the_date, '%W, %b. %d, %y') |
+-----------------------------------------+
| Tuesday, Nov. 02, 21 |
| Wednesday, Jan. 05, 22 |
| Tuesday, May. 03, 22 |
| Friday, Jan. 13, 23 |
+-----------------------------------------+
4 rows in set (0.00 sec)
```
### Conclusion
This tutorial should give you a helpful overview of date and time values in MySQL. I hope that this article has taught you something new that allows you to have both better control and a greater understanding into how your MySQL database handles temporal values.
--------------------------------------------------------------------------------
via: https://opensource.com/article/23/2/temporal-values-mysql
作者:[Hunter Coleman][a]
选题:[lkxed][b]
译者:[hanszhao80](https://github.com/hanszhao80)
校对:[校对者ID](https://github.com/校对者ID)
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
[a]: https://opensource.com/users/hunterc
[b]: https://github.com/lkxed/
[1]: https://opensource.com/downloads/mariadb-mysql-cheat-sheet

View File

@ -0,0 +1,203 @@
[#]: subject: "Rust Basics Series #6: Conditional Statements"
[#]: via: "https://itsfoss.com/rust-if-else/"
[#]: author: "Pratham Patel https://itsfoss.com/author/pratham/"
[#]: collector: "lkxed"
[#]: translator: " "
[#]: reviewer: " "
[#]: publisher: " "
[#]: url: " "
Rust Basics Series #6: Conditional Statements
======
In the [previous article][1] in this series, you looked at Functions. In this article, let's look at managing the control flow of our Rust program using conditional statements.
### What are conditional statements?
When writing some code, one of the most common tasks is to perform a check for certain conditions to be `true` or `false`. "If the temperature is higher than 35°C, turn on the air conditioner."
By using keywords like `if` and `else` (sometimes in combination), a programmer can change what the program does based on conditions like the number of arguments provided, the options passed from the command line, the names of files, error occurrence, etc.
So it is critical for a programmer to know control flow in any language, let alone in Rust.
#### Conditional operators
The following table shows all the frequently used operators for an individual condition:
| Operator | Example | Interpretation |
| :- | :- | :- |
| `>` | `a > b` | `a` is **greater** than `b` |
| `<` | `a < b` | `a` is **less** than `b` |
| `==` | `a == b` | `a` is **equal** to `b` |
| `!=` | `a != b` | `a` is **not equal** to `b` |
| `>=` | `a >= b` | `a` is **greater than** OR **equal** to `b` |
| `<=` | `a <= b` | `a` is **less than** OR **equal** to `b` |
And following is the table for logical operators, they are used between one or more conditions:
| Operator | Example | Interpretation |
| :- | :- | :- |
| `||` (Logical OR) | `COND1 || COND2` | At least one of the condition `COND1` or `COND2` evaluates to `true` |
| `&&` (Logical AND) | `COND1 && COND2` | **All** conditions evaluate to `true` |
| `!` (Logical NOT) | `!COND` | Opposite boolean value of what `COND` evaluates to |
> 📋 Like in Mathematics, you can use parentheses (round brackets) to specify the precedence of an operation compared to others.
### Using if else
To handle the basic flow of Rust code, two keywords are used: `if` and `else`. This helps you create two "execution paths" based on the state of the provided condition.
The syntax of a simple if block with an alternative execution path is as follows:
```
if condition {
<statement(s)>;
} else {
<statement(s)>;
}
```
> 📋 When only one condition is provided, enclosing it in round brackets is not compulsory. The use of round brackets is optional, according to the syntax. You should still use them to specify precedence and for better readability.
Let's look at an example.
```
fn main() {
let a = 36;
let b = 25;
if a > b {
println!("a is greater than b");
} else {
println!("b is greater than a");
}
}
```
Here, I have declared two integer variables `a` and `b` with the values '36' and '25'. On line 5, I check if the value stored in variable `a` is greater than the value stored in variable `b`. If the condition evaluates to `true`, the code on line 6 will be executed. If the condition evaluates to `false`, due to the fact that we have an `else` block (which is optional), the code on line 8 will get executed.
Let's verify this by looking at the program output.
```
a is greater than b
```
Perfect!
Let's modify the value of variable `a` to be less than value of variable `b` and see what happens. I will change `a`'s value to '10'. Following is the output after this modification:
```
b is greater than a
```
But, what if I store the same value in variables `a` and `b`? To see this, I will set both variables' value to be '40'. Following is the output after this particular modification:
```
b is greater than a
```
Huh? Logically, this doesn't make any sense... :(
But this can be improved! Continue reading.
### Using 'else if' conditional
Like any other programming language, you can put an `else if` block to provide more than two execution paths. The syntax is as follows:
```
if condition {
<statement(s)>;
} else if condition {
<statement(s)>;
} else {
<statement(s)>;
}
```
Now, with the use of an `else if` block, I can improve the logic of my program. Following is the modified program.
```
fn main() {
let a = 40;
let b = 40;
if a == b {
println!("a and b are equal");
} else if a > b {
println!("a is greater than b");
} else {
println!("b is greater than a");
}
}
```
Now, the logic of my program is correct. It has handled all edge cases (that I can think of). The condition where `a` is equal to `b` is handled on line 5. The condition where `a` might be greater than `b` is handled on line 7. And, the condition where `a` is less than `b` is intrinsically handled by the `else` block on line 9.
Now, when I run this code, I get the following output:
```
a and b are equal
```
Now that's perfect!
### Example: Find the greatest
I know that the use of `if` and `else` is easy, but let us look at one more program. This time, let's compare three numbers. I will also make use of a logical operator in this instance!
```
fn main() {
let a = 73;
let b = 56;
let c = 15;
if (a != b) && (a != c) && (b != c) {
if (a > b) && (a > c) {
println!("a is the greatest");
} else if (b > a) && (b > c) {
println!("b is the greatest");
} else {
println!("c is the greatest");
}
}
}
```
This might look complicated at first sight, but fear not; I shall explain this!
Initially, I declare three variables `a`, `b` and `c` with random values that I could think of at that time. Then, on line 6, I check for the condition where no variable's value is same as any other variable. First, I check the values of `a` and `b`, then `a` and `c` and then `b` and `c`. This way I can be sure that there are no duplicate values stored in either variable.
Then, on line 7, I check if the value stored in variable `a` is the greatest. If that condition evaluates to `true`, code on line 8 gets executed. Otherwise the execution path on line 9 is checked.
On line 9, I check if the value stored in variable `b` is the greatest. If this condition evaluates to `true`, code on line 10 gets executed. If this condition is also `false`, then it means only one thing. Neither variable `a`, nor variable `b` is the greatest among all 3.
So naturally, in the `else` block, I print that the variable `c` holds the greatest value.
Let's verify this with the program output:
```
a is the greatest
```
And this is as expected. Try and modify the values assigned to each variable and test it out yourself! :)
### Conclusion
You learned to use if and else statements. Before you go on making your own AI with lost of if else-if statements (haha), let' learn about loops in Rust in the next chapter of the series.
Stay tuned.
--------------------------------------------------------------------------------
via: https://itsfoss.com/rust-if-else/
作者:[Pratham Patel][a]
选题:[lkxed][b]
译者:[译者ID](https://github.com/译者ID)
校对:[校对者ID](https://github.com/校对者ID)
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
[a]: https://itsfoss.com/author/pratham/
[b]: https://github.com/lkxed/
[1]: https://itsfoss.com/rust-functions