javascript – Node.js – 设置系统日期/时间

有没有办法从node.js服务器设置操作系统上的日期/时间?

有很多关于如何更改时区的示例,但我需要更改PC的实际日期/时间

最佳答案 我的回答是基于@Mimouni在另一个问题上回答
https://stackoverflow.com/a/23156354/1799272,我刚刚将sys的include更改为util,因为弃用了.

此外,由于我们的实现和要求(如果时间错误,我们启动其他Windows服务)我导入了’node-windows’.但是,如果您只想使用内置的npm功能,欢迎您查看是否可以提升用户.

基本上你有3个重要的步骤:

>将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);

如果您想设置时间,请将exec中的日期替换为时间.

点赞