How do I set time and date from the Internet?

A small code I found to update your time in case you don't want to install anything just to update the date. :)

sudo date -s "$(wget -qSO- --max-redirect=0 google.com 2>&1 | grep Date: | cut -d' ' -f5-8)Z"

You can use :

sudo dpkg-reconfigure tzdata

for configuring your timezone .

For updating time and date from internet use the following :

Install

If ntpd is not installed use any one of the following command to install ntpd:

  • For RPM based:

    yum install ntp 
    
  • For Debian based:

    sudo apt-get install ntp
    

Configuration

You should at least set following parameter in /etc/ntp.conf config file: server

For example, open /etc/ntp.conf file using vi text editor:

  # vi /etc/ntp.conf

Locate server parameter and set it as follows:

  server pool.ntp.org

Save the file and restart the ntpd service:

  # /etc/init.d/ntpd start

You can synchronize the system clock to an NTP server immediately with following command:

  # ntpdate pool.ntp.org

*For setting the time and date manually use the following syntax:

 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"

To set time use the following syntax:

# date +%T -s "10:13:13"

Where,

10: Hour (hh) 13: Minute (mm) 13: Second (ss)

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"

I use this:

sudo ntpd -qg; sudo hwclock -w

first tell ntpd to just set the time and stop after that with -q. Also, in case a your clock has a big error we need to tell ntpd to also adjust in that case with -g. Finally write the clock to hardware to preserve the changes when rebooting with hwclock -w (-w for setting hardwareclock to current system time, there is a difference).