javascriptc++node.jsv8node.js-nan

Conversion between v8::value to date


I am writing C++ addon on v8 using nan. One of the arguments to constructor is of Date type. IsDate returns true, but I don't know how to convert it to C++ Date object to get Year, Month and Day and etc..

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

Thanks for your helping!


Solution

  • You can cast a v8 Value to a Date object with the v8::Date::Cast function.

    From there you can extract the number of milliseconds since the Unix epoch (1st January 1970) with the NumberValue function.

    Then convert this number to a std::time_t object by casting the number of seconds static_cast<time_t>(millisSinceEpoch/1000)

    From the time_t get a struct *tm with the localtime function.

    Then finally extracting the day/month/year values:

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