ChakraCore.NET icon indicating copy to clipboard operation
ChakraCore.NET copied to clipboard

new Date() 和C#代码转换

Open 527395632 opened this issue 4 years ago • 5 comments

new Date() 返回的JsValue的类型是Object对象, 它如何跟C#中的DateTime相互转换呢?

527395632 avatar Dec 16 '20 05:12 527395632

Hi, Github上建议用英语来沟通。 中文问题我会尽量双语回答, 包括把问题翻译成英语,但是这样工作量有些大,建议以后用英语来提问。

[ENG] Question: The return type of new Date() is JsValue which is an Object type, how to use it as DateTime in C#?

Answer: [ENG]DateTime value transfer is a build-in feature , You can use read it directly as DateTime C# code:

context.RunScript("var dd=new Date();");
DateTime d=context.GlobalObject.ReadProperty<DateTime>("dd");

[中文] DateTime的类型转换是内置的,你可以直接用DateTime来读取JS里面的日期值 C# code:

context.RunScript("var dd=new Date();");
DateTime d=context.GlobalObject.ReadProperty<DateTime>("dd");

JohnMasen avatar Dec 22 '20 07:12 JohnMasen

Thank you very much for the help of "John Masen". I did a test as soon as I received the reply, and the result was abnormal. The specific code is as follows:

Program.cs

    static void Main(string[] args)
    {
        using (var runtime = ChakraRuntime.Create(JavaScriptRuntimeAttributes.None))
        using (var context = runtime.CreateContext(false))
        {
            context.RunScript("var dd=new Date();");
            DateTime d = context.GlobalObject.ReadProperty<DateTime>("dd");
        }
    }

The file throwing the exception is line 88 of "JSValueConverterService.cs", which means that there is no converter of this type. How do you implement it? Is it because I didn't operate correctly? image image

527395632 avatar Dec 22 '20 12:12 527395632

after checking the source code, I found the DateTime converter was removed, can't remember why. Anyway, I will add it back soon and keep you updated.

JohnMasen avatar Dec 23 '20 08:12 JohnMasen

That's great, thank you very much!

527395632 avatar Dec 23 '20 09:12 527395632

issue solved, please sync with latest code. NuGet package updated.

JohnMasen avatar Dec 23 '20 14:12 JohnMasen