We recently ran an article on the Linux “date” command. It’s a pretty cool command line tool that allows you to get your system’s date and time in various formats. What it also does is it allows you to set the machine’s date and time. Let’s look at a couple of ways to set the time and date on a Linux machine. First, we’ll look at how to do it using the “date” command, then I’ll briefly introduce you to the NTP server in Linux and show you how you can sync your machine’s clock to a clock running on the Internet.
First, a brief recap on what the “date” command can do for you:
Mon Dec 22 22:35:58 IST 2008
Now if you want to change the machine’s date to 1:45 PM on Christmas day in the year 2008, here’s how you would do it:
# date -s “25 DEC 2008 13:45:00″
Thu Dec 25 13:45:02 IST 2008
This above command is pretty self-explanatory. But to make it clear, here’s the breakup. First comes the “date” command. Then you use the “-s” option, which stands for “set date”. After that you enter the date you want to set in the following order. “Date Month Year Hours:Minutes:Seconds”. After entering this hit the return key. The system should revert with the new date. Now you can enter the “date” command once again to make sure that the date is set right.
There are a number of other ways to do this same thing. As you might have read in my previous article about the “date” command, it is pretty versatile. You can do something similar as what we just tried above with a slightly different syntax:
#date +%Y%m%d -s “20081225″
This will set the system’s date to the 25th of December, 2008.
The other method I use to set my computer’s date is using the NTP server. NTP stands for Network Time Protocol. NTPd is a daemon that runs on most Linux machines. When configured correctly this daemon allows you to connect to a Time server over the network (your local network or the Internet) and synchronize the time. It’s very commonly used for production servers.
It’s pretty likely that your Linux machine is already equipped with NTP. If not, install it using your system’s preferred installation method.
Ubuntu users can use the following command:
# sudo apt-get install ntpdate
Fedora users can probably use this:
# yum install ntp
Once NTPd is installed on your computer open the file /etc/ntp.conf in your favorite text editor. In this file locate a line containing the “server” parameter. Set it to the following address:
Save the file and restart your NTP server.
# /etc/init.d/ntpd restart
You can now synchronize your machine to the time server you just configured:
# ntpdate pool.ntp.org
22 Dec 23:07:00 ntpdate: step time server 220.127.116.11 offset 172868.246157 sec
Now your machine will quickly talk to the time server you assigned it and get you the right time. This way you know for sure that the time on your machine is accurately set. It may be a good idea to run this command every once in a while to make sure you’re on time.