How do I manually set the time to a UTC timestamp in Linux?

3

If I want to set the time I know I can use a command like this:

sudo date +%T -s '17:45:00'

And it will set the clock to 5:45pm in the system time zone. This means that if I have the system set to UTC this will be 17:45 UTC, but if the system is set to Eastern time then the same command would actually update the clock to be 12:45 UTC. Is there some way I can specify the timezone identifier along with the time, in the date -s command?

soapergem

Posted 2018-01-26T16:19:07.643

Reputation: 1 056

What version of date are you using? This doesn't match the documentation of date that I'm reading. And why are you doing this at all? – Michael Hampton – 2018-01-26T18:03:07.570

Looks like the version is 8.2.3. It's what came installed on Raspbian. – soapergem – 2018-01-26T20:37:18.623

Answers

1

After a bit of trial-and-error experimentation, I figured it out. To set just the time and to force it to be in UTC, I can do this:

sudo date +%T%Z -s "17:45:00UTC"

If I want to set the date and the time simultaneously, I can do this:

sudo date -s '2018-01-26T17:45:00Z'

soapergem

Posted 2018-01-26T16:19:07.643

Reputation: 1 056

It's all in the man page. Both -d and -s take a "date string" and its format is described (actually a very permissive input). You can use date -d as a dry run for date -s – xenoid – 2018-01-26T21:34:09.847

1

In most flavors of Linux (Particularly Redhat/Centos off the top of my head), do this:

# Delete the current time zone file
rm -f /etc/localtime

# Set it to the new value
ln -s /usr/share/zoneinfo/UTC /etc/localtime

I understand that this does not use the date command as you requested.

UtahJarhead

Posted 2018-01-26T16:19:07.643

Reputation: 1 755

1

If the device you are updating the time on, does not have a connection to the internet. And you don't care about sub-seconds accuracy. You can use this on a computer with a known correct time to generate a bash command that sets the correct time using UTC timestamp.

echo "date +%s -s @$(date +%s)"

This will generate something like date +%s -s @1541377821 that you can copy and paste to the other computer.

Brian

Posted 2018-01-26T16:19:07.643

Reputation: 111

Underrated answer, this saved me some keystrokes :) – pilkch – 2019-02-08T00:39:06.420