Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add x seconds to the current date in Linux

Tags:

I have two Linux (CentOS 6.0) machines over here and I need to add (or remove) 5 seconds to the current date time. In the end, both my machines would have a gap of 5 seconds (one with the right time and the other one with 5 seconds more or less).

I know I can change the date with this command:

date -s "DD MMM YYYY HH:MM:SS"

but I need to be precise and it will be hard for me to run the command at the right time.

So I'd like to know if there is a way in general to add 5 seconds to the current time, a bit like when you choose your time zone compared to Greenwich (+5 hours in my case).

like image 755
Cocotton Avatar asked Mar 12 '12 15:03

Cocotton


People also ask

How do I run a Linux script in 5 seconds?

What you could do is write a shell script with an infinite loop that runs your task, and then sleeps for 5 seconds. That way your task would be run more or less every 5 seconds, depending on how long the task itself takes. You can create a my-task.sh file with the contents above and run it with sh my-task.sh .

How do I convert date to seconds in Linux?

You could even use date +%s , which apparently gives the seconds since 1970-01-01 00:00:00 UTC .


2 Answers

You can add 5 seconds to the current time in one command using date -s "5 seconds".

The full manual regarding all of the date input formats that all of GNU coreutils accepts can be found online at https://www.gnu.org/software/coreutils/manual/html_node/Date-input-formats.html.

like image 67
Jonathan Callen Avatar answered Sep 30 '22 02:09

Jonathan Callen


Actually, Linux comes with a handy function to return a time plus a modifier.

date --date='5 seconds'

You can test it from the command line with a simple

date && date --date='5 seconds'

Using this you can just write a small batch file that sets a variable to the time you want and then runs the set command.

EDIT: here's a bash script that will do it for you. It needs to be run as root

#!/bin/bash

NEWDATE=`date +%T --date '5 seconds'`;
date +%T -s "$NEWDATE";
like image 41
Nathan Cox Avatar answered Sep 30 '22 01:09

Nathan Cox