Clearscript: Evaluation of expression "new Date()" returns unexptected result

Created on 23 Jun 2019  路  2Comments  路  Source: microsoft/ClearScript

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

Most helpful comment

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!

All 2 comments

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!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

roblarky picture roblarky  路  3Comments

grumpydev picture grumpydev  路  5Comments

Bobris picture Bobris  路  6Comments

huyphams picture huyphams  路  4Comments

JohnLudlow picture JohnLudlow  路  4Comments