- 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
- 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?
- Getting date and time of system startup in Linux
- 12 Answers 12
- Get current time in seconds since the Epoch on Linux, Bash
- 7 Answers 7
- Pure bash solution
- Learn Linux, 101: Maintain system time
- Keep your system in step
- Overview
- Inside your system clock
- Prerequisites
- Dates and times
- Display and set the system date and time
- Displaying date and time
- Setting date and time
- Set the hardware clock to UTC
- Configure your time zone
- Configure the Network Time Protocol
- NTP commands
- Time and time zone management with systemd
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
Источник
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
Источник
Getting date and time of system startup in Linux
I know that uptime prints the time a machine has been up and running, but is there an easier (reliable) way to get the date of the start up than counting down from this output?
I tried looking around /proc , but didn’t find anything of relevance. There’s also a line like this on my dmesg :
But I’m wondering if this method is distribution and kernel version agnostic?
12 Answers 12
I found some commands here. Try who -b or last reboot | head -1 .
who gives numeric dates, while last reboot returns abbreviated day / month names.
This queries the uptime from the kernel and displays it in the local timezone:
Be careful about other options. The last command will stop working as soon as wtmp has been rotated. The who command depends on the availability and integrity of utmp . And /proc/1 might have the current date instead of the boot time date, and could even be unavailable on a hardened system. Edit: dmesg only has a fixed-length back buffer, so it is unrealiable, too. The kernel logs may be in /var/log but most distributions only keep 8 weeks of them.
I stumbled on this question while looking for a way to get a consistent, parseable boot time, as opposed to time since boot which changes on every call.
It appears that uptime -s will do the trick on most linux systems.
Источник
Get current time in seconds since the Epoch on Linux, Bash
I need something simple like date , but in seconds since 1970 instead of the current date, hours, minutes, and seconds.
date doesn’t seem to offer that option. Is there an easy way?
7 Answers 7
This should work:
Get the seconds since epoch(Jan 1 1970) for any given date(e.g Oct 21 1973).
Convert the number of seconds back to date
The command date is pretty versatile. Another cool thing you can do with date(shamelessly copied from date —help ). Show the local time for 9AM next Friday on the west coast of the US
So far, all the answers use the external program date .
Since Bash 4.2, printf has a new modifier %(dateformat)T that, when used with argument -1 outputs the current date with format given by dateformat , handled by strftime(3) ( man 3 strftime for informations about the formats).
So, for a pure Bash solution:
or if you need to store the result in a variable var :
No external programs and no subshells!
Since Bash 4.3, it’s even possible to not specify the -1 :
(but it might be wiser to always give the argument -1 nonetheless).
If you use -2 as argument instead of -1 , Bash will use the time the shell was started instead of the current date. This can be used to compute elapsed times
Pure bash solution
Since bash 5.0 (released on 7 Jan 2019) you can use the built-in variable EPOCHSECONDS .
There is also EPOCHREALTIME which includes fractions of seconds.
EPOCHREALTIME can be converted to micro-seconds (μs) by removing the decimal point. This might be of interest when using bash ‘s built-in arithmetic (( expression )) which can only handle integers.
In all examples from above the printed time values are equal for better readability. In reality the time values would differ since each command takes a small amount of time to be executed.
With most Awk implementations:
This is an extension to what @pellucide has done, but for Macs:
To determine the number of seconds since epoch (Jan 1 1970) for any given date (e.g. Oct 21 1973)
Please note, that for completeness, I have added the time part to the format. The reason being is that date will take whatever date part you gave it and add the current time to the value provided. For example, if you execute the above command at 4:19PM, without the ’00:00:00′ part, it will add the time automatically. Such that «Oct 21 1973» will be parsed as «Oct 21 1973 16:19:00». That may not be what you want.
Источник
Learn Linux, 101: Maintain system time
Keep your system in step
By Ian Shields
Updated September 28, 2017 | Published September 27, 2017
Overview
In this tutorial, learn to:
- Set the system date and time
- Set the hardware clock to the correct time in UTC
- Configure the correct time zone
- Perform basic NTP configuration
- Use the pool.ntp.org service
- Understand the ntpq command
Inside your system clock
When you install a Linux® system graphically, you set the clock and choose a time zone suitable for your needs. You can also choose to use the Network Time Protocol (NTP) to set your clock automatically, and you can choose to have the system clock use Coordinated Universal Time (UTC) rather than local time. This tutorial shows you how to go below the graphical interfaces and configure the various time-related aspects of your Linux system.
About this series
This series of tutorials helps you learn Linux system administration tasks. You can also use the material in these tutorials to prepare for the Linux Professional Institute’s LPIC-1: Linux Server Professional Certification exams.
See “ Learn Linux, 101: A roadmap for LPIC-1” for a description of and link to each tutorial in this series. The roadmap is in progress and reflects the version 4.0 objectives of the LPIC-1 exams as updated on April 15th, 2015. As tutorials are completed, they will be added to the roadmap.
This tutorial helps you prepare for Objective 108.1 in Topic 108 of the Linux Server Professional (LPIC-1) exam 102. The objective has a weight of 3.
Prerequisites
To get the most from the tutorials in this series, you need a basic knowledge of Linux and a working Linux system on which you can practice the commands covered in this tutorial. You should be familiar with GNU and UNIX® commands. Sometimes different versions of a program format output differently, so your results might not always look exactly like the listings shown here.
Unless otherwise noted, I use Fedora 26 running Wayland and Ubuntu 16.04 LTS or CentOS 6 running X11 for the examples in this tutorial.
Dates and times
Calendars have existed for thousands of years, mostly based on the regular courses of the sun and the moon. Sundials have been used since ancient times to mark the passage of time during a day. Time was sometimes disseminated by ringing bells to announce hours or times of prayer. Mechanical clocks have been powered by water, springs, and pendulums among other things. A great improvement in accuracy came with the use of the quartz crystal oscillator. Atomic clocks (now based on ytterbium) are now the most accurate clocks. Reference sources are maintained by national standards organizations. Time is now disseminated to computers from these primary sources using NTP.
Display and set the system date and time
System time on a Linux system is very important. The cron and anacron facilities perform tasks based on time, so they need an accurate clock to base decisions on. Most backup and restore tools, along with development tools such as make , also depend on reliable time measurements. Computers built since around 1980 usually include some kind of clock mechanism, and most built since 1984 or so have a persistent clock mechanism that keeps time even if the computer is turned off.
You can use graphical tools to display or set the clock if your system has a graphical interface such as Wayland or the X Window System. Figure 1 shows an example from a GNU Network Object Model Environment (GNOME) desktop.
Figure 1. Updating the date and time graphically
In the remainder of this tutorial, I show you how to get under the hood and use command-line tools to manage your time and time zone settings as well as your hardware clock.
Displaying date and time
No matter whether you live in New York, Budapest, Nakhodka, Ulaanbaatar (formerly anglicised as Ulan Bator), Bangkok, or Canberra, most of your Linux time computations are related to Coordinated Universal Time or UTC. Listing 1 shows you how to use the date command to display the current date and time. The default display is always in local time, even if your hardware clock keeps UTC. Use the -u option to display UTC. Besides UTC, the date command supports a wide variety of possible output formats. See the man page for date if you’d like to learn more about the various date formats.
Listing 1. Displaying the current date and time
Use the -d (or —date ) option to display the date for some particular time, such as next Tuesday, or for a particular time zone. The input format is quite flexible, although it is currently restricted to locale-independent formats. Use LC_TIME=C if necessary. Listing 2 shows several examples.
Listing 2. Displaying other dates and times
Use the output formatting options of the date command to control how you want the output displayed. Listing 3 shows some examples. The info pages for the date command contain several other examples of using the date command and a lot more information.
Listing 3. Date output formats
Setting date and time
If you need to set the date, you provide a date and time string as an argument. The required format is historical and is somewhat odd even to Americans and truly odd to the rest of the world. You must specify at least month, day, hour, and minute in MMDDhhmm format, and you can also append a two- or four-digit year (CCYY or YY) and optionally a period (.) followed by a two-digit number of seconds. Listing 4 shows an example that alters the system date by 5 minutes. Note that you need to have root authority to change the date or time.
Listing 4. Setting the system date and time
On GNU systems you can also set the system clock using date strings that are acceptable to the -d option of the date command. Use the -s (or —set ) option. For example, you can set the clock ahead by 5 minutes using the command,
date —set=’+5 minutes’
Note: Neither -s nor -d options accept the MMDDhhmm format described above.
Set the hardware clock to UTC
Most Linux systems, along with other current operating systems, actually have two clocks. The first is the internal software clock, which is driven by counting system interrupts. It is subject to variations caused by high system load and interrupt latency. The second is the hardware clock, sometimes called the Real Time Clock (RTC) or hardware clock, which is usually tied to an oscillating quartz crystal that is accurate to within a few seconds per day. It is subject to variations such as ambient temperature. Your system typically reads the hardware clock at start up and from then on uses the software clock. The date command that you just learned about sets the software clock, not the hardware clock.
Note: A hardware clock needs battery power to maintain status when the system is turned off. The battery is typically a common coin-sized battery. There are some systems, for example Raspberry Pi, that do not have a hardware clock but can run Linux. These are usually connected to the Internet to update time. I will show you more about Internet time protocols later in this tutorial.
If you run a dedicated Linux system, it is customary to keep the hardware clock set to UTC, but if you also boot another operating system such as Microsoft® Windows®, you might need to set the hardware clock to local time. Mostly it doesn’t matter as far as Linux is concerned, except that the hardware clock doesn’t know about Daylight Saving Time (DST). So, if your Linux system isn’t running when a DST change occurs, then your time will probably be off when it next starts unless you have automatic time zone setting enabled.
If you use NTP, you may possibly set the hardware clock when you first install the system and never worry about it again. If not, this part of the tutorial will show you how to display and set the hardware clock if you have one.
The hwclock command (without any options) shows the current value of the hardware clock. Listing 5 shows the current value of both the system and hardware clocks.
Listing 5. System and hardware clock values
Notice that the two values differ by 5 minutes. When you use the date command to update the system time, the hardware clock is not affected. Thus the 5 minute difference.
You can synchronize the hardware clock from the system clock using the -w or —systohc option of hwclock , and you can synchronize the system clock from the hardware clock using the —set or —hctosys option, as shown in Listing 6.
Listing 6. Setting the system clock from the hardware clock
You can use the —set option together with the —date option and a date string to specify an absolute or relative date for the hardware clock.
When setting the hardware clock, specify the —utc option to have the hardware clock kept in UTC or the —localtime option to have it kept in local time. If neither is specified, the value is taken from the third line of /etc/adjtime, if that file exists.
The Linux kernel has a mode that copies the system time to the hardware clock every 11 minutes. This is off by default, but is turned on by NTP. Running anything that sets the time the old-fashioned way, such as hwclock –hctosys hwclock—hctosys , turns it off, so it is a good idea to just let NTP do its work if you are using NTP. See the man page for adjtimex to find out how to check whether the clock is being updated every 11 minutes or not. You may need to install the adjtimex package as it is not always installed by default.
The hwclock command keeps track of changes made to the hardware clock in order to compensate for inaccuracies in the clock frequency. The necessary data points are kept in /etc/adjtime, which is an ASCII file. If you are not using NTP, you can use the adjtimex command to compensate for clock drift. Otherwise, the hardware clock will be adjusted approximately every 11 minutes by NTP. Besides showing whether your hardware clock is in local time or UTC, the first value in /etc/adjtime shows the amount of hardware clock drift per day (in seconds). Listing 7 shows an example.
Listing 7. /etc/adjtime showing clock drift and local time or UTC
Note that this system keeps the hardware clock in UTC.
Configure your time zone
Your time zone is a measure of how far your local time differs from UTC. Information on available time zones that can be configured is kept in /usr/share/zoneinfo. Traditionally, /etc/localtime is a link to one of the time zone files in this directory tree, for example, /usr/share/zoneinfo/Eire or /usr/share/zoneinfo/Australia/Hobart. Some systems, such as Ubuntu, use a copy of the file rather than a link.
Many countries or regions also use daylight savings. Dates for daylight savings changes can vary from year to year and from place to place. So, keeping your clock correctly set relative to UTC has become quite complex.
Another file, /etc/timezone, was traditionally a link to /etc/default/init and was used to set the time zone environment variable, TZ , and several locale-related environment variables. The file may or may not exist on your system. If it does, it may just contain the name of the current time zone. Finally, some systems also have time zone information in /etc/sysconfig/clock.
Listing 8 shows /etc/timezone and /etc/localtime links on a Ubuntu 16.04 system.
Note: Fedora systems do not have /etc/timezone.
Listing 8. Time zone information in /etc
To set the time zone correctly, you need to know the appropriate zone name. Use the txselect command to determine this interactively as shown in Listing 9.
Listing 9. Using tzselect interactively
Now that you know your time zone, you can change it for a single user as described at the end of the output shown in Listing 9. If you want to change the system time zone there are different ways on different types of system as I explain below.
For Debian-based systems such as Ubuntu, the recommended method is to use dpkg-reconfigure tzdata dpkg-reconfiguretzdata , which uses an interactive dialog that first asks for the continent and then the city that you want to set the time zone for. Listing 10 shows the console output if I reset my Ubuntu system’s time zone to Asia/Ulaanbaatar and also the values for /etc/timezone and /etc/localtime. Figure 2 shows part of the dialog.
Listing 10. Using dpkg-reconfiguretzdata
Figure 2. Selecting a city using dpkg-reconfigure tzdata
For RPM-based systems such as CentOS 6 that do not use systemd initialization, you manually update /etc/localtime. Recall that this is usually a link to a file in the /usr/share/zoneinfo tree. The link can be either a hard link or a symbolic link. It can only be a hard link if /etc and /usr are mounted on the same file system. If you look at the number of links roa time zone file in a long directory listing, you will notice that many zones already have multiple links. These represent different names for the same time zone, for example /usr/share/zoneinfo/Asia/Calcutta and /usr/share/zoneinfo/Asia/Kolkata are two names for India Standard Time. Listing 11 explores my current timezone and shows how to change it to Kolkata time using a hard link.
Listing 11. Updating the link for /etc/localtime
For RPM-based systems such as Fedora 26 that use systemd initialization, use the datetimectl command that is discussed in the section, .
Configure the Network Time Protocol
The Network Time Protocol (NTP) is a protocol to synchronize computer clocks over a network. Synchronization is usually with UTC. NTP Version 4 is an Internet standard formalized in RFC 5905.
Time synchronization is accomplished by sending messages to time servers. A limited number of primary servers are synchronized with national standard time sources. Secondary servers get their time from primary servers or from other secondary servers. Client systems get their time from a secondary server. Secondary servers and clients on fast LANs can be accurate to within a few hundred microseconds. Simple Network Time Protocol (SNTP) is intended for primary servers equipped with a single reference clock, and for clients with a single upstream server and no dependent clients. The full NTP implementation is intended for secondary servers with multiple upstream servers and multiple downstream servers or clients. NTP and SNTP servers and clients are interoperable and can be intermixed.
The general operation is for a client to send a packet to a server, noting the time it is sent. The server marks the time the packet is received and also the time that a return packet is sent. The client notes the time the response is received. The client can then deduct the delay in the server from the total round trip. Half the round trip is then assumed as the difference between the client time and the server time. The accuracy of the time is therefore dependent on the network latency and the extent to which the latency is the same in both directions. The shorter the path to a time server, the more accurate the time is likely to be.
There is a huge number of computers on the Internet, so time servers are organized into strata. A relatively small number of stratum 1 servers maintain very accurate time from a source such as an atomic clock. These are usually primary servers. A larger number of stratum 2 servers (secondary servers) get their time from stratum 1 servers and make it available to an even larger number of stratum 3 servers, and so on. The pool.ntp.org project is a virtual cluster of time servers providing the default time server for most of the major Linux distributions and many networked appliances. Round robin DNS servers accomplish NTP load balancing by distributing NTP server requests among a number of available servers.
The configuration of NTP and examples in the remainder of this section use CentOS 6 with upstart system initialization. Systems, such as my Fedora 26 or Ubuntu 16.04 LTS workstations use systemd initialization and manage time synchronization somewhat differently as I will show you in the next section.
If you use a graphical interface, you might be able to set your NTP time servers using a dialog similar to that in Figure 3.
Figure 3. Setting NTP servers graphically
NTP configuration information is kept in /etc/ntp.conf, so you can also edit that file and then restart the ntpd daemon after you save it. Listing 12 shows an example /etc/ntp.conf file using the time servers from Figure 3.
Listing 12. Example /etc/ntp.conf
Your distribution should have set up host names such a 0.vendor.pool.ntp.org, 1.vendor.pool.ntp.org, 2.vendor.pool.ntp.org, and 3.vendor.pool.ntp.org to use time servers from pool.ntp.org. These may be anywhere in the world. NTP is designed to find a suitable server for you.
Each host name in the pool usually resolves to a few different servers using IPV4 or IPV6 protocols. The servers change frequently to help balance load. Listing 13 shows the DNS responses for 2.centos.pool.ntp.org at the particular time I ran the command and then again a few hours later.
Listing 13. Round robin NTP server pool
NTP commands
The ntpdate command can set your system time from an NTP time server as shown in Listing 14. If the ntpd service is already running you see an error. In this case, stop the ntpd service first as I illustrate here.
Listing 14. Setting system time from an NTP server using ntpdate
The ntpdate command is now deprecated. Indeed, the man page typically says: “After a suitable period of mourning, the ntpdate program is to be retired from this distribution”. Use the ntpd command with the -q option, to perform the equivalent function. This causes the ntpd daemon to start and then to exit after setting the clock. Be aware that if the ntpd daemon is already running, ntpd -q ntpd-q will quietly exit, leaving a failure message in /var/log/messages as shown in Listing 15.
Listing 15. Setting system time using ntpd-q
The ntpd command uses the time server information from /etc/ntp.conf, or a configuration file provided on the command line. See the man page for more information and details about ntpd .
Another related command is ntpq , which allows you to query the NTP daemon, mainly for debugging purposes. The -p option is a handy way of printing out the peers currently known to the NTP server and some basic information about them. Listing 16 shows an example with server names in numeric (dotted decimal) format. See the man page for more details.
Listing 16. Listing peer time servers using ntpq
The ‘refid’ column shows the source that the peer is using and the ‘st’ column shows the stratum of that source. ‘Reach’ is an octal number indicating how many queries were successful with 377 being the best value. For more information on NTP debugging, install the ntp-doc package. On my CentOS 6 system, this installs a set of HTML files rooted at /usr/share/doc/ntp-4.2.6p5/html.
Time and time zone management with systemd
As with many of the internals of Linux, some of the information I have covered has changes or alternatives if your system uses the systemd system and service manager. In this final section I cover some of the things you should know about the changes, although they are not part of the April 2015 LPI objectives.
The examples in this section are from Ubuntu 16.04 LTS.
Systemd includes systemd-timesyncd.service by default. You can check whether the services is running using the systemctl command as shown in Listing 17.
Listing 17. Using systemctl status systemd-timesyncd.service
Systemd-timesyncd.service implements a Simple NTP (SNTP) client. The systemd porting guide advises systems to request a vendor NTP pool from pool.ntp.org and the default NTP servers are compiled in. See the DISTRO_PORTING file (typically /usr/share/doc/systemd/DISTRO_PORTING). The small configuration file as shown in Listing 18 allows you to override the default time servers and also to provide backup servers.
Listing 18. Using timesyncd.conf
Use the timedatectl command to interact with systemd-timesyncd.service. You can get status information using the status command of timedatectl as shown in Listing 19.
Listing 19. Status information using timedatectl
Other timedatectl commands allow you to set the time or time zone and also list available time zones. You can also use timedatectl to enable or disable NTP time synchronization.
Systemd-timesyncd.service does not provide as much accuracy as a full NTP daemon, although it is sufficiently accurate for most systems. You can use specific servers in the timesyncd.conf file to help provide better accuracy or you install an NTP daemon such as openntpd. If you do, you will need to disable systemd-timesyncd.service. Also, do not use timedatectl as you inadvertently stop your ntpd daemon.
This concludes your introduction to time settings on Linux. We have come a long way from the days of depending on the bell tower in the town square for time information!
Источник