How can I set the time on my Linux machine?

So your Linux server is up and running, but the time is off. Or it starts out fine when you reboot but wanders off after that. No prob; it happens all the time.

I have two main ways to set time on a Linux system: Using the “date” command itself, or using NTP as either a deamon/client or just a routine call to a remote daemon (perhaps via cron). Confused? Nah, follow along…

  • Date Command :

If you just want to set it by command line, type “date [MMddhhmm]” with the correct valules there. For example, right now it is “date 12041554“. You don’t need year, as long as the year is correct. If you *do* need the year, just tack it on the end, like this “date 1204155407“.

  • NTP Daemon/Client:

First, type “ntpq -pn” to show the status of your local ntp daemon. It should show the remote ntp server that it is sync’d against, and there should be an asterisk to the left. If it’s not working right (like if you get a “connection refused” message), that means you are not running the daemon locally, and it might need to be addressed (that is a whole post in itself, about the “ntp.conf” and such). If you expect the daemon to be running locally, just restart it and it may be fine. Then you get to figure out why it stopped… 😉

Second, if you know of a remote time server that you might want to sync to, for instance 2.pool.ntp.org, you would type “ntpq -pn 2.pool.ntp.org” just to make sure the daemon is running and sync’d. Look for an asterisk to the left again to verify that your trusted remote time server is in sync.

If you are happy that you trust that server, you can type “ntpdate 2.pool.ntp.org” and that will sync your machine to it. Now, you can put that command in a cron job if you need to, especially if you don’t want to mess with the reason why your ntp daemon keeps failing right now… like because your bios battery has been dead since 1996 and the time goes back to 1980 every time you reboot…

Hmm… maybe one of the next posts should be more in-depth about NTP…

P.S…. by the way, if you just want to see both the hardware clock and the system time in one quick display, use this:
hwclock -r;date

And, if you have correctly adjusted the system time and want to adjust the hardware clock to match, use this:

hwclock -w

🙂

1 Comment

  1. Steve

    Thank you for posting this. I just used it to solve an issue. Thanks again to creating this blog…

Leave a Comment

Your email address will not be published. Required fields are marked *