最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Node.js - Set system datetime - Stack Overflow

programmeradmin1浏览0评论

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

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

Share Improve this question asked Mar 29, 2017 at 9:28 Donovan BoddyDonovan Boddy 5081 gold badge6 silver badges14 bronze badges 8
  • What is the purpose of changing the time? – str Commented Mar 29, 2017 at 9:30
  • 1 @mplungjan how is this a duplicate question? Have you even bothered to read the question you say its a duplicate of? – Donovan Boddy Commented Mar 29, 2017 at 9:48
  • The puter that the Node.js server will be running on has to keep in time with other PC's on the network, to within a second or so. – Donovan Boddy Commented Mar 29, 2017 at 9:51
  • You want to run a system mand from node. The duplicate I posted shows you how. How is it not a duplicate? Did you even look at it? I reopened... – mplungjan Commented Mar 29, 2017 at 10:03
  • @mplungjan my apologies, it seems that job would be what i am looking for – Donovan Boddy Commented Mar 29, 2017 at 12:07
 |  Show 3 more ments

1 Answer 1

Reset to default 2

My answer is based of of @Mimouni's answer https://stackoverflow./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 wele 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:

  1. Convert str/int to the date you want
  2. Format the date correctly
  3. run the elevated mand

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.

发布评论

评论列表(0)

  1. 暂无评论