2

Is there a way / library that can change the system time? In my case I need to update the time of a linux machine (Debian). I know there is a way to set the time with a shell command, what I am asking is if there is an abstraction library or another way?

giusti
  • 3,156
  • 3
  • 29
  • 44
Kristofar
  • 71
  • 1
  • 3
  • The Unix system call to do this is `settimeofday`. See if you can find a library that provides a way to call it. I did a couple of google searches and didn't find anything. – Barmar Sep 27 '19 at 16:55

1 Answers1

2

It's pretty simple if you use your machine's date command. However, to do this, you'll need to call the system command from your NodeJS script. That is possible with NodeJS's exec command. You can read more about it here. It's basically a way to call system function from inside your NodeJS code. It runs asyncronous, so it requires a callback that has NodeJS error, stdout, and stderror.

const { exec } = require('child_process');

const timestamp = '20190927 10:00:00';

exec(`/bin/date --set="${timestamp}"`, (err, stdout, stderr) => {
  if (err || stderr) {
    console.error(err);
    console.log(stderr);
  } else {
    console.log(stdout);
    console.log(`Successfully set the system's datetime to ${stdout}`);
  }
}));

Likely you won't have a $PATH available. Therefore, you'll need to specify the exact path to date. You can find that by running which date in a terminal and copying the output into the exac statement. For my Ubuntu 18.04 machine, it's located in /bin/date.

technogeek1995
  • 3,185
  • 2
  • 31
  • 52
  • This has an extra `)` on the end. Also this method does not seem to work in at least some Docker containers. It yields an error: `/bin/date: cannot set date: Operation not permitted` – defraggled Sep 26 '21 at 05:09