When I evaluate "var theDate = new Date();", I expect a DateTime object indicating the current date and time, but what I receive is a Microsoft.ClearScript.Undefined. Below is the code:
using Microsoft.ClearScript.V8;
using System;
namespace ClearScriptDemo
{
class Program
{
static void Main(string[] args)
{
using (var engine = new V8ScriptEngine())
{
object result = engine.Evaluate("var theDate = new Date();");
Console.WriteLine("Result: {0}", result);
Console.ReadKey();
}
}
}
}
Hi @tu-lehong,
There are two issues here.
First, JavaScript's var statement doesn't produce or return a value. To work around that, you can use an assignment instead:
``` C#
object result = engine.Evaluate("theDate = new Date();");
Or, if you must use `var`, you can end your script with an expression:
``` C#
object result = engine.Evaluate("var theDate = new Date(); theDate;");
Second, V8ScriptEngine doesn't convert JavaScript Date into .NET DateTime by default. However, you can enable that with a flag:
``` C#
using (var engine = new V8ScriptEngine(V8ScriptEngineFlags.EnableDateTimeConversion))
{
object result = engine.Evaluate("theDate = new Date();");
Console.WriteLine("Result: {0}", result);
Console.ReadKey();
}
```
Good luck!
Many thanks!
Most helpful comment
Hi @tu-lehong,
There are two issues here.
First, JavaScript's
varstatement doesn't produce or return a value. To work around that, you can use an assignment instead:``` C#
object result = engine.Evaluate("theDate = new Date();");
Second,
V8ScriptEnginedoesn't convert JavaScriptDateinto .NETDateTimeby default. However, you can enable that with a flag:``` C#
using (var engine = new V8ScriptEngine(V8ScriptEngineFlags.EnableDateTimeConversion))
{
object result = engine.Evaluate("theDate = new Date();");
}
```
Good luck!