1

我正在使用 nan 在 v8 上编写 C++ 插件。构造函数的参数之一是 Date 类型。IsDate 返回 true,但我不知道如何将其转换为 C++ Date 对象以获取年、月和日等。

void NodeObject::New(const Nan::FunctionCallbackInfo<v8::Value>& info) {
    if(info[0]->IsDate()) {
        //convert and get year, month and day
        boost::gregorian::date d(2016 , 1 ,1);
        double price = getPrice(date);
    }
}

感谢您的帮助!

4

1 回答 1

1

您可以使用v8::Date::Cast函数将 v8 值转换为 Date 对象。

从那里您可以使用该函数提取自 Unix 纪元(1970 年 1 月 1 日)以来的毫秒数NumberValue

然后通过转换秒数将此数字转换为std::time_t对象static_cast<time_t>(millisSinceEpoch/1000)

time_t获取带有localtime函数的struct *tm 。

然后最后提取日/月/年值:

void NodeObject::New(const Nan::FunctionCallbackInfo<v8::Value>& info) {
  if(info[0]->IsDate()) {
    double millisSinceEpoch = v8::Date::Cast(*info[0])->NumberValue(); 
    std::time_t t = static_cast<time_t>(millisSinceEpoch/1000);

    struct tm* ltime = localtime(&t);
    int year = ltime->tm_year + 1900;
    int month = ltime->tm_mon + 1;
    int day = ltime->tm_mday;

    boost::gregorian::date d(year, month, day);  
    double price = getPrice(date);         
  }
}
于 2016-04-20T22:45:56.577 回答