diff --git a/napi-inl.h b/napi-inl.h index 0f1717ecd..e9fcf82bc 100644 --- a/napi-inl.h +++ b/napi-inl.h @@ -20,6 +20,9 @@ #endif // NAPI_HAS_THREADS #include #include +#if __cplusplus >= 201103L +#include +#endif #if defined(__clang__) || defined(__GNUC__) #define NAPI_NO_SANITIZE_VPTR __attribute__((no_sanitize("vptr"))) @@ -1199,6 +1202,15 @@ inline Date Date::New(napi_env env, double val) { return Date(env, value); } +#if __cplusplus >= 201103L +inline Date Date::New(napi_env env, std::chrono::system_clock::time_point tp) { + using namespace std::chrono; + auto ms = static_cast( + duration_cast(tp.time_since_epoch()).count()); + return Date::New(env, ms); +} +#endif + inline void Date::CheckCast(napi_env env, napi_value value) { NAPI_CHECK(value != nullptr, "Date::CheckCast", "empty value"); diff --git a/napi.h b/napi.h index 013a9114d..3f0fde54d 100644 --- a/napi.h +++ b/napi.h @@ -19,6 +19,9 @@ #endif // NAPI_HAS_THREADS #include #include +#if __cplusplus >= 201103L +#include +#endif // VS2015 RTM has bugs with constexpr, so require min of VS2015 Update 3 (known // good version) @@ -685,6 +688,12 @@ class Date : public Value { double value ///< Number value ); + /// Creates a new Date value from a std::chrono::system_clock::time_point. + static Date New( + napi_env env, ///< Node-API environment + std::chrono::system_clock::time_point tp ///< Time point value + ); + static void CheckCast(napi_env env, napi_value value); Date(); ///< Creates a new _empty_ Date instance. diff --git a/test/date.cc b/test/date.cc index efd433af4..2fa59b50e 100644 --- a/test/date.cc +++ b/test/date.cc @@ -1,3 +1,7 @@ +#if __cplusplus >= 201103L +#include +#endif + #include "napi.h" using namespace Napi; @@ -11,6 +15,13 @@ Value CreateDate(const CallbackInfo& info) { return Date::New(info.Env(), input); } +#if __cplusplus >= 201103L +Value CreateDateFromTimePoint(const CallbackInfo& info) { + auto input = std::chrono::system_clock::time_point{}; + return Date::New(info.Env(), input); +} +#endif + Value IsDate(const CallbackInfo& info) { Date input = info[0].As(); @@ -35,6 +46,7 @@ Value OperatorValue(const CallbackInfo& info) { Object InitDate(Env env) { Object exports = Object::New(env); exports["CreateDate"] = Function::New(env, CreateDate); + exports["CreateDateFromTimePoint"] = Function::New(env, CreateDate); exports["IsDate"] = Function::New(env, IsDate); exports["ValueOf"] = Function::New(env, ValueOf); exports["OperatorValue"] = Function::New(env, OperatorValue); diff --git a/test/date.js b/test/date.js index 86c8af6ac..80f69208b 100644 --- a/test/date.js +++ b/test/date.js @@ -12,6 +12,7 @@ function test (binding) { OperatorValue } = binding.date; assert.deepStrictEqual(CreateDate(0), new Date(0)); + assert.deepStrictEqual(CreateDateFromTimePoint(), new Date(0)); assert.strictEqual(IsDate(new Date(0)), true); assert.strictEqual(ValueOf(new Date(42)), 42); assert.strictEqual(OperatorValue(new Date(42)), true);