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
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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With