当前位置:首页 » 《我的小黑屋》 » 正文

Linux date命令详解:如何设置、更改、格式化和显示日期时间(附实例与注意事项)

6 人参与  2024年05月06日 16:22  分类 : 《我的小黑屋》  评论

点击全文阅读


Linux date命令介绍

date命令在Linux中用来显示和设置系统日期和时间。这个命令允许用户以不同的格式打印时间,也可以计算未来和过去的日期。

Linux date命令适用的Linux版本

date命令在所有主流的Linux发行版中都可以使用,包括但不限于Debian、Ubuntu、Alpine、Arch Linux、Kali Linux、RedHat/CentOS、Fedora和Raspbian。无需特别的安装过程,因为date是Linux内置的程序。

Linux date命令的基本语法

date命令的语法格式如下:

date [options]... [+format]

Linux date命令的常用选项或参数说明

选项说明
-d允许用户操作具体的日期
–date显示给定的日期字符串格式
–set更改系统时钟
–file印出文件里的每一行的日期字符串
-r打印文件最后修改时间
+%s显示从1970/01/01 00:00:00 UTC到现在为止的秒数

Linux date命令实例详解

实例1:显示当前的系统时间和日期

[linux@bashcommandnotfound.cn ~]$ date

实例2:操作具体日期

[linux@bashcommandnotfound.cn ~]$ date -d "2000-11-22 09:10:15"

实例3:显示给定的日期字符串作为日期格式

[linux@bashcommandnotfound.cn ~]$ date --date="09/10/1960"

实例4:设置或更改Linux中的时间

[linux@bashcommandnotfound.cn ~]$ date --set="20100513 05:30"

实例5:显示过去的日期

[linux@bashcommandnotfound.cn ~]$ date --date="2 year ago"[linux@bashcommandnotfound.cn ~]$ date --date="yesterday"[linux@bashcommandnotfound.cn ~]$ date --date="10 sec ago"

实例6:显示未来的日期

[linux@bashcommandnotfound.cn ~]$ date --date="next monday"[linux@bashcommandnotfound.cn ~]$ date --date="4 day"[linux@bashcommandnotfound.cn ~]$ date --date="tomorrow"

实例7:自定义格式显示日期

[linux@bashcommandnotfound.cn ~]$ date +"Year: %Y, Month: %m, Day: %d"[linux@bashcommandnotfound.cn ~]$ date "+DATE: %D%nTIME: %T"[linux@bashcommandnotfound.cn ~]$ date +"Week number: %V Year: %y"

实例8:显示文件最后修改时间

[linux@bashcommandnotfound.cn ~]$ date -r /etc/hosts

实例9:更改时间区域为New York时间

[linux@bashcommandnotfound.cn ~]$ TZ='America/New_York' date

实例10:使用date命令创建包含当前时间和日期的文件名

[linux@bashcommandnotfound.cn ~]$ mysqldump database_name > database_name-$(date +%Y%m%d).sql

实例11:在shell脚本中使用date命令

下面我们将date命令的输出分配给date_now变量:

[linux@bashcommandnotfound.cn ~]$ date_now=$(date "+%F-%H-%M-%S")

实例12:使用date命令作为Epoch转换器

Epoch,或Unix时间戳,是从1970年1月1日00:00:00 UTC到目前为止的秒数。

[linux@bashcommandnotfound.cn ~]$ date +%s[linux@bashcommandnotfound.cn ~]$ date -d "1984-04-08" +"%s"

Linux date命令的注意事项

使用date命令需要注意:

date命令默认使用操作系统的时区,除非另有指定。使用–date选项不会影响系统的实际日期和时间值,它只是打印请求的日期。在设置系统时钟时要谨慎,因为多数Linux发行版已经使用NTP或systemd-timesyncd服务同步系统时钟了。

如果遇到“bash: date: command not found”的错误提示,那就按照上面的步骤安装相关程序即可。

Linux date相关命令

cal命令:用于显示日历
tzselect命令:用于查看或更改系统时区
timedatectl命令:用于管理和配置系统时间和日期
printf命令:用于格式化并打印数据


点击全文阅读


本文链接:http://zhangshiyu.com/post/104284.html

<< 上一篇 下一篇 >>

  • 评论(0)
  • 赞助本站

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

关于我们 | 我要投稿 | 免责申明

Copyright © 2020-2022 ZhangShiYu.com Rights Reserved.豫ICP备2022013469号-1