Node.js-设置系统日期/时间 [英] Node.js - Set system date / time

查看:679
本文介绍了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的答案< a href = https://stackoverflow.com/a/23156354/1799272> 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:


  1. 将str / int转换为所需日期

  2. 正确格式化日期

  3. 运行提升权限的命令

这里是:

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.

这篇关于Node.js-设置系统日期/时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆