- DateTime
- See the time
- Set the time manually
- Setting the hardware clock
- Set the time automatically
- Installing NTP
- Hardware clock and system time when dual booting
- Display Date And Time In Linux
- Syntax
- Display date and time in Linux using the timedatectl
- TZ environment variable
- GUI Tool: Time Administration
- How to change date and time settings with Gnome based Linux desktop
- Conclusion
- ⏲️ 8 примеров команды date на Linux
- Базовый синтаксиc
- 1) Команда date без параметров
- 2) Отображение даты и времени в формате UTC
- 3) Отображение определенной даты в строковом формате
- 4) Использование команды date, чтобы проверить прошлые даты
- 5) Использование команды date, чтобы проверить будущие даты
- 6) Параметры форматирования даты
- 7) Как установить дату и время
- 8) Использование команды Date в переменной
- Заключение
- Linux Set Date and Time From a Command Prompt
- Linux Display Current Date and Time
- Linux Display The Hardware Clock (RTC)
- Linux Set Date Command Example
- Linux Set Time Examples
- How do I set the Hardware Clock to the current System Time?
- A note about systemd based Linux system
- timedatectl: Display the current date and time
- How do I change the current date using the timedatectl command?
- How do I set the current time only?
- How do I set the time zone using timedatectl command?
- How do I synchronizing the system clock with a remote server using NTP?
- DateTime
See the time
To see the time on a Debian GNU/Linux system, use the command date, without arguments it will show system time respecting the currently defined timezone.
To see the time in the UTC timezone, use the command date --utc (or shorthand date -u). See the date manual page.
Set the time manually
When setting the system time manually using date directly, the required time specification format may be confusing (by POSIX convention has to be MMDDhhmmYYYY). However, when using the --set argument date accepts the date and time in many formats. You can read the man page of date, or use the example below for one possible and very useful format. The —set argument examples below is specified in the ISO 8601 standard’s extended format as YYYY-MM-DD for Year-Month-DayOfMonth, and time of day HH:MM:SS using 24 hour clock. Leading zeros are significant.
The above two commands set the system date to second of November, 1998, and system time to eight minutes past nine, PM.
Note, using the date command only sets the runtime system time (aka. software clock) but has no effect on the underlying hardware clock (aka. RTC = real time clock). When the system boots, it has no concept of absolute time and will populate the system time with the date and time read from the hardware clock, thus to ensure that the time set using date is kept across reboots it has to be saved to the hardware clock.
Most desktop environments provide a date/time configuration utility. See also the time-admin program in gnome-system-tools package.
Setting the hardware clock
To write the current system time to the hardware clock so that it can be recovered on subsequent restarts of the system, correct the system time as above, then use the command hwclock --systohc to save it to hardware (see the hwclock manual page for more options).
Modern Debian releases (2.2 and onwards) automatically save the system time to hardware clock on proper shutdowns, and set the system clock from hardware clock when they boot up. This is done by the script /etc/init.d/hwclock.sh.
Set the time automatically
The protocol used to set the time is the Network Time Protocol or NTP. To set the time automatically you need access to an NTP server. Your local network may provide such a server but most people need to access an NTP server via the internet.
On the internet there are time servers that provide the correct time. Your ISP may provide a time service and this would be your closest and probably most accurate source. While there are still many independent NTP servers you can connect to, the best source is http://pool.ntp.org.
Installing NTP
It’s really quite easy on Debian.
Because the pool is global, you should adjust
where XX is your continent or two letter country code. Click on the continent to see the valid country codes. eg CA for Canada etc.
For increased accuracy you would include extra server lines such as
incrementing the number for each line. Two or three should be all you need.
Hardware clock and system time when dual booting
While Debian prefer to keep the hardware clock in UTC (this prevents the need to change it on daylight savings and timezone changes) other systems (like Windows) by default keeps the hardware clock synchronized to local time. To keep the hardware clock sane and the time correctly displayed by multiple systems they need to agree on which timezone the hardware clock is kept at.
In Debian the timezone for the hardware clock is configured in the file /etc/adjtime;
Edit /etc/adjtime, and change «UTC» to «LOCAL» if you want the hardware clock to be kept at local time instead of UTC.
- You need to use sudo or su to edit this file. Any editor will work, but nano or vi is the normal choice.
Источник
Display Date And Time In Linux
H ow do I display date and time in Linux using the command line and GUI options?
To display date and time under Linux operating system using command prompt use the date command. It can also display the current time / date in the given FORMAT. We can set the system date and time as root user too.
Tutorial details | |
---|---|
Difficulty level | Easy |
Root privileges | No |
Requirements | Linux with the terminal application |
Est. reading time | 3 minutes |
Syntax
Open a terminal and type the following command:
date
You can format the date as follows in dd-mm-yy format:
date +»%d-%m-%y»
Simply display the current time:
date «+%T»
- No ads and tracking
- In-depth guides for developers and sysadmins at Opensourceflare✨
- Join my Patreon to support independent content creators and start reading latest guides:
- How to set up Redis sentinel cluster on Ubuntu or Debian Linux
- How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
- How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
- A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
- How to protect Linux against rogue USB devices using USBGuard
Join Patreon ➔
To print the date of the day before yesterday, run:
date —date=’2 days ago’
Want to see the day of year of Christmas in the current year? Try:
date —date=’25 Dec’ +%j
Display the current full month name and the day of the month:
date ‘+%B %d’
Display date and time in Linux using the timedatectl
Most modern Linux distro with systemd use the timedatectl command. It is used to query and change the system clock and its settings, and enable or disable time synchronization services. All you have to do is type the following command:
$ timedatectl
TZ environment variable
The TZ environment tells Linux what time zone you are in. Many times when you want to change your time zone temporarily. For example, you might want to print the current date and time in “America/Los_Angeles” timezone even though you are in “Europe/London”. So we can set TZ, give a command like as follows when using TCSH/CSH:
setenv TZ timezone
For BASH/KSH/SH (see export command:
TZ=timezone; export TZ
Another option:
TZ=»America/Los_Angeles» date
TZ=»Asia/Tokyo» date
Use the following command to print a list of all timezones:
timedatectl list-timezones
timedatectl list-timezones | more
## filter out data using the grep command/egrep command ##
timedatectl list-timezones | grep -i Hong_kong
timedatectl list-timezones | grep -i paris
timedatectl list-timezones | grep -E -i ‘paris|london|kolkata’
The TZ Environment Variable on Linux
GUI Tool: Time Administration
The Time Administration Tool allows you to set the time, date and timezone of your system, as well as setting any time server to synchronize your local time server. Type the following command to start time admin tool:
sudo time-admin
## OR ##
time-admin
Fig.01: Linux Date and Time Administration Tool
How to change date and time settings with Gnome based Linux desktop
First, you need to Settings in Activities and then click Details in the sidebar. Make sure you click Date & Time in the sidebar to open the panel:
Conclusion
In this quick tutorial, you learned about the date command that you can use to see or change the date/time under Linux operating systems. We further explained how to use the GUI tools too. The date command has many more options. See man page by typing the following man command:
$ man date
🐧 Get the latest tutorials on Linux, Open Source & DevOps via
Источник
⏲️ 8 примеров команды date на Linux
Базовый синтаксиc
Базовый синтаксис команды date представлен ниже:
1) Команда date без параметров
2) Отображение даты и времени в формате UTC
Чтобы отобразить время в формате UTC (всемирное координированное время), ранее называвшееся GMT (среднее время по Гринвичу), добавьте параметр -u.
3) Отображение определенной даты в строковом формате
4) Использование команды date, чтобы проверить прошлые даты
Команда date также может выводить дату и время в прошлом относительно вашей текущей даты.
Например, чтобы проверить дату 9 дней назад, выполните команду.
5) Использование команды date, чтобы проверить будущие даты
Так же, как вы можете проверять прошлые даты, команда date также позволяет отображать будущие даты.
Например, чтобы узнать дату завтрашнего дня:
6) Параметры форматирования даты
- %D – Отображение даты в формате мм / дд / гг
- %Y – Год (например, 2021 г.)
- %m – Месяц (01-12)
- %B – Название месяца в формате полной строки (например, February)
- %b –Название месяца в сокращенном строковом формате (например, Feb).
- %d – День месяца (например, 01)
- %j – День года (001-366)
- %u – День недели (1-7)
- %A –День недели в формате полной строки (например, Friday)
- %a – День недели в сокращенном формате (например, Fri)
- %H – Час (00-23)
- %I – Час (01-12)
- %M – Mинута (00-59)
- %S – Секунда (00-60)
Синтаксис использования опции date довольно прост:
Чтобы вывести день недели, месяц, год и текущее время:
7) Как установить дату и время
Команда date также позволяет вам установить дату и время.
Например, чтобы установить дату и время на 25 июня 2021 года в 11:15, выполните команду:
Такой способ установки даты и времени в системе не рекомендуется, поскольку время, скорее всего, будет неточным.
Лучший способ добиться этого – использовать утилиту chrony, которая является заменой устаревшего демона ntpd.
Фактически, современные системы, такие как CentOS 8/RHEL 8, не поддерживают NTP.
У нас есть подробное руководство о том, как синхронизировать время и дату с помощью chrony.
Если вы хотите изменить часовой пояс, используйте команду timedatectl, пример показан ниже.
8) Использование команды Date в переменной
Заключение
Мы надеемся, что пролили свет на использование команды date на Linux, и надеемся, что вы сможете использовать ее для отображения даты в системе и настройки вывода по своему усмотрению.
Источник
Linux Set Date and Time From a Command Prompt
H ow can I set the system date and time from the command prompt (bash shell)? I don’t have GUI installed and I am login over ssh session. How can I set date under Linux operating systems?
Use the date command to display the current date and time or set the system date / time over ssh session. You can also run the date command from X terminal as root user.
Tutorial details | |
---|---|
Difficulty level | Easy |
Root privileges | Yes |
Requirements | None |
Est. reading time | 2m |
This is useful if the Linux server time and/or date is wrong, and you need to set it to new values from the shell prompt.
You must login as root user to use date command.
Linux Display Current Date and Time
Just type the date command:
$ date
Sample outputs:
Linux Display The Hardware Clock (RTC)
Type the following hwclock command to read the Hardware Clock and display the time on screen:
# hwclock -r
OR
# hwclock —show
$ sudo hwclock —show —verbose
OR show it in Coordinated Universal time (UTC):
# hwclock —show —utc
Sample outputs:
Linux Set Date Command Example
Use the following syntax to set new data and time:
date —set=»STRING»
For example, set new data to 2 Oct 2006 18:00:00, type the following command as root user:
# date -s «2 OCT 2006 18:00:00»
OR
# date —set=»2 OCT 2006 18:00:00″
You can also simplify format using following syntax:
# date +%Y%m%d -s «20081128»
Linux Set Time Examples
To set time use the following syntax:
# date +%T -s «10:13:13»
Where,
Use %p locale’s equivalent of either AM or PM, enter:
# date +%T%p -s «6:10:30AM»
# date +%T%p -s «12:10:30PM»
How do I set the Hardware Clock to the current System Time?
Use the following syntax:
# hwclock —systohc
OR
# hwclock -w
A note about systemd based Linux system
With systemd based system you need to use the timedatectl command to set or view the current date and time. Most modern distro such as RHEL/CentOS v.7.x+, Fedora Linux, Debian, Ubuntu, Arch Linux and other systemd based system need to the timedatectl utility. Please note that the above command should work on modern system too.
timedatectl: Display the current date and time
Type the following command:
$ timedatectl
Fig.01: Systemd Linux timedatecetl command to display the current date and time
How do I change the current date using the timedatectl command?
To change the current date, type the following command as root user:
# timedatectl set-time YYYY-MM-DD
OR
$ sudo timedatectl set-time YYYY-MM-DD
For example set the current date to 2015-12-01 (1st, Dec, 2015):
# timedatectl set-time ‘2015-12-01’
# timedatectl
Sample outputs:
To change both the date and time, use the following syntax:
# timedatectl set-time YYYY-MM-DD HH:MM:SS
Where,
- HH : An hour.
- MM : A minute.
- SS : A second, all typed in two-digit form.
- YYYY: A four-digit year.
- MM : A two-digit month.
- DD: A two-digit day of the month.
For example, set the date ’23rd Nov 2015′ and time to ‘8:10:40 am’, enter:
# timedatectl set-time ‘2015-11-23 08:10:40’
# date
- No ads and tracking
- In-depth guides for developers and sysadmins at Opensourceflare✨
- Join my Patreon to support independent content creators and start reading latest guides:
- How to set up Redis sentinel cluster on Ubuntu or Debian Linux
- How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
- How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
- A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
- How to protect Linux against rogue USB devices using USBGuard
Join Patreon ➔
How do I set the current time only?
The syntax is:
# timedatectl set-time HH:MM:SS
# timedatectl set-time ’10:42:43′
# date
Sample outputs:
How do I set the time zone using timedatectl command?
To see list all available time zones, enter:
$ timedatectl list-timezones
$ timedatectl list-timezones | more
$ timedatectl list-timezones | grep -i asia
$ timedatectl list-timezones | grep America/New
To set the time zone to ‘Asia/Kolkata’, enter:
# timedatectl set-timezone ‘Asia/Kolkata’
Verify it:
# timedatectl
How do I synchronizing the system clock with a remote server using NTP?
Simply type the following command:
# timedatectl set-ntp yes
Verify it:
$ timedatectl
Sample outputs:
Conclusion
Linux users can use date command to print or set the system date and time. Systemd based Linux users can use timedatectl to control the system time and date.
- You can also set new timzone using this mini-howto.
- Man pages – timedatectl(8)
🐧 Get the latest tutorials on Linux, Open Source & DevOps via
Источник