Quantcast
Channel: ClearScript
Viewing all articles
Browse latest Browse all 2297

Commented Unassigned: Exception when creating Dates in V8ScriptEngine [113]

0
0
Hello,

I'm trying to create/parse date from a JS evaluate and return them as strings back into c# code as such:

```
using (var engine = new V8ScriptEngine())
{
resultEval = engine.Evaluate(expression);
}
```

where my `expression` is

`new Date()`

and it return an "Microsoft.ClearScript.V8.V8ScriptItem" object with an "UnderlyingSystemType" saying:

'((Microsoft.ClearScript.ScriptItem)resultEval).UnderlyingSystemType' threw an exception of type 'System.NotImplementedException'

Now, I feel like this *should* work, but it's not. Any ideas? I don't think anything went wrong during the build/reference process. Other JS libraries such as Math work flawlessly.

Also, this is only an issue when trying to create a `new` date. Calling `Date()` works, but it only displays today's date.
Comments: Hi again, ​ >Now, I understand you can't flat out return a JavaScript Date object into .NET and expect it to work, so the issue is with the return type. But then why does Date() work? Is it implementing DateTime.Now? I think that's a bit confusing. ​ Sorry about the confusion. ClearScript doesn't convert automatically between JavaScript's `Date` and .NET's `DateTime`. It aims instead to provide full access to all objects on both sides. You ask why `new Date()` works. It works because it's 100% valid JavaScript. To evaluate it, ClearScript invokes the V8 script engine, but it isn't involved beyond that. Now, when a `Date` or any other script object is returned to the host, ClearScript wraps it in a [dynamic](https://msdn.microsoft.com/en-us/library/dd264736.aspx) proxy that provides full access to the script object. Here's a sample that demonstrates the best way to convert `DateTime` to `Date` in script code and perform the opposite conversion in C#: ``` C# // create .NET DateTime var clrNow = DateTime.Now; Console.WriteLine(clrNow); // .NET DateTime -> JavaScript Date engine.Script.clrNow = clrNow; engine.AddHostType(typeof(Console)); engine.Execute(@" jsNow = new Date(clrNow.ToUniversalTime().ToString('o')); Console.WriteLine(jsNow.toString()); "); // JavaScript Date -> .NET DateTime dynamic jsNow = engine.Script.jsNow; var clrNow2 = DateTime.Parse(jsNow.toISOString()); Console.WriteLine(clrNow2); ``` Good luck!

Viewing all articles
Browse latest Browse all 2297

Latest Images

Trending Articles





Latest Images