Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js - Set system date / time

Is there a way to set the date/time on the operating system from a node.js server?

There are plenty of examples on how to change the time-zone but i need to change the actual date / time of the PC

like image 741
Donovan Boddy Avatar asked Oct 29 '22 10:10

Donovan Boddy


1 Answers

My answer is based of of @Mimouni's answer https://stackoverflow.com/a/23156354/1799272 on a different question, I just changed the include of sys to util, because of deprecation.

Furthermore due to our implementation and requirements (we start other windows services if the time was wrong) I imported 'node-windows'. However you are welcome to see if you can elevate the user without this if you only want to use built in npm features.

basically you have 3 important steps:

  1. Convert str/int to the date you want
  2. Format the date correctly
  3. run the elevated command

Here as follows:

const sys = require('util')
const win = require('node-windows')

dateTime    = new Date(time) //Convert string or number to date
let day     = dateTime.getDate() 
let month   = dateTime.getUTCMonth() + 1 
let year    = dateTime.getFullYear() 
let updateD = `${year}-${month}-${day}` //Format the string correctly

//Add a callback function (this can be somewhere else)
function execCallback(error, stdout, stderr) { 
     if (error) {
         console.log(error)
     } else {
         console.log(stdout) 
     }
}
var exec = win.elevate(`cmd /c date ${updateD}`,undefined, execCallback);

if you wish to set the time, replace date in the exec with time.

like image 84
Oli4 Avatar answered Nov 09 '22 23:11

Oli4