Node.js-设置系统日期/时间
是否可以通过node.js服务器在操作系统上设置日期/时间?
Is there a way to set the date/time on the operating system from a node.js server?
关于如何更改时间的示例很多-zone,但是我需要更改PC的实际日期/时间
There are plenty of examples on how to change the time-zone but i need to change the actual date / time of the PC
我的答案基于@Mimouni的答案 https://stackoverflow.com/a/23156354/1799272 在另一个问题上,我只是将sys的包含更改为util
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.
此外,由于我们的实现和要求(如果时间不正确,我们将启动其他Windows服务),因此我导入了 node-windows。但是,如果您只想使用内置的npm功能,欢迎您查看是否可以在没有此功能的情况下提升用户。
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.
基本上,您拥有3个重要步骤:
basically you have 3 important steps:
- 将str / int转换为所需日期
- 正确格式化日期
- 运行提升权限的命令
这里是:
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);
如果要设置时间,请用以下命令替换执行中的 date 时间。
if you wish to set the time, replace date in the exec with time.