Node.js - Set System Date / Time
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 to share