根据日期/时间有条件地运行代码

时间:2014-12-17 22:08:31

标签: javascript node.js datetime time

我正在构建一个使用Instagram API的基于事件的应用程序。由于应用程序是基于事件的,我只想回复Instagram在特定日期和时间发送给我的回调的Instagram API POST。我的攻击计划是将console.log('callback hit');之后的所有代码包含在条件声明if(current day/time <= upper bound && current day/time >= lower bound) {run code} else {console.log('event is not currently in progress')}中。我的问题是a)这是一种合乎逻辑的方法吗?和b)我将如何引用&#34;上/下限&#34;和&#34;当前日期/时间&#34;,即如何正确编码特定日期/时间?

以下代码位于我的节点&#39; server.js&#39;文件:

app.post('/callback', function (req, res) {
  console.log('callback hit');

  //loop in all the new objects
  req.body.forEach(function (data) {
    console.log('received POST info');

    if (data.changed_aspect !== 'media') { 
      console.log('not an image');
      return;
    }

    request('https://api.instagram.com/v1/geographies/' + data.object_id + '/media/recent?client_id=' + clientID,
      function (error, response, body) {
        if (error) { 
          console.log('error');
          return;
        }

        console.log('request sent to Instagram');
        //Here we have one JSON object with all the info about the image
        var image = JSON.parse(body);
        console.log(image.data[0]);

        //Save the new object to DB
        Stadium.findOneAndUpdate( {object_id: data.object_id}, { $push: {'photos':
          { img: image.data[0].images.standard_resolution.url,
            link: image.data[0].link,
            username: image.data[0].user.username,
            profile: image.data[0].user.profile_picture,
            text: image.data[0].caption ? image.data[0].caption.text : ''
          }}},
          { safe: true, upsert: false },
          function(err, model) {
            console.log(err);
          }
        );

        //Send a socket to client with the new image
        newImage({
          img: image.data[0].images.standard_resolution.url,
          link: image.data[0].link,
          username: image.data[0].user.username,
          profile: image.data[0].user.profile_picture,
          text: image.data[0].caption ? image.data[0].caption.text : ''
        });
      }
    );
  });

  res.end();

});

1 个答案:

答案 0 :(得分:1)

我会做这样的事情:

if (new Date('12-15-2014') <= Date.now() <= new Date('12-31-2014')) {
  // your code here. i.e handleEvent();
}
else {
  // nothing happens here
}

只需使用Date对象设置日期范围即可。作为一个注释,我还建议在包含方法中移动逻辑只是为了清理一下条件。

希望这有帮助!