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 many examples of how to change the time zone, but I need to change the actual date / time of the PC.

+3


source to share


1 answer


My answer is based on @ Mimouni's fooobar.com/questions/55581 / ... answer to another question, I just changed the sys inclusion to use due to fatigue.

Also, due to our implementation and requirements (we start other Windows services if the timing was wrong) I imported 'node-windows'. However, you can see if you can elevate the user without this if you want to use npm's built-in functions.

basically you have 3 important steps:

  • Convert str / int to desired date
  • Format the date correctly.
  • execute command with elevated rights


Here:

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 want to set time, replace date in exec with time .

0


source







All Articles