Show current date and time on linux

Sometimes a virtual maschine or your server can run into the wrong date or time. That happens for example if you don't restart a virtual maschine but just pause it.

To show the current date and time just enter the following:

$ date

which output's something like:

Mo  8 Sep 2014 11:43:54 CEST

To reset it you could use the following script, which you can put into a file called

#! /bin/bash

OFFSET=`/usr/sbin/ntpdate -q | grep ntpdate | awk '{print $10}' | awk -F '.' '{print $1}'`

if [ $OFFSET -ge 120 ]
    echo "Date outdated: $OFFSET"
    echo "Adjust date"
    /etc/init.d/ntp stop \
        && /usr/sbin/ntpdate -s
    /etc/init.d/ntp start
    exit 0

echo "Time `date `"
exit 0

When you're working with local cronjobs, you're able to run this script every five minutes. Open your cronlist editor with:

$ sudo crontab -e

And enter the following line:

*/5 * * * * /usr/bin/sudo /bin/bash /path/to/your/ &> /dev/null

Your system needs to have an active internet connection for the script to work. Otherwise you will get an error which will get swallowed by piping it to /dev/null. If you're having problems with this, the following articles might help you:

Restarting network interfaces on your console