2

I am able to call C# methods of WebBrowser.ObjectForScripting with javascript window.external from WebBrowser WinForms control and pass string, int, bool etc. However I don't know how to pass javascript Date object and somehow convert/marshal it to .NET DateTime class.

Obviously, I could pass a string and parse it, but this is really not the point. I'm just curious how could I do it with javascript Date and .NET DateTime?

3 Answers 3

3

You can take advantage of the fact that dates in Javascript are expressed as the number of milliseconds elapsed since the UNIX epoch (1970-01-01 00:00:00 UTC). Use the valueOf() method to obtain that value from a Date object :

var millisecondsSinceEpoch = yourDate.valueOf();

If you can marshal that value to C# as a double, you can create the appropriate DateTime object using its constructor and the AddMilliseconds() method:

DateTime yourDateTime = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)
    .AddMilliseconds(millisecondsSinceEpoch);
Sign up to request clarification or add additional context in comments.

3 Comments

I could do that, but I am looking only for solution for how to read javascript Date object in C#. I'm not even sure if that's possible, but if it's not, that's ok. But I'm hoping that there is some way to do that.
There are no "Javascript Date objects" in C#
As far as I understand, when I pass Date object to C# it's marshaled using COM, so I suppose it's possible to do it.
1

I finally got it working. I don't know why, but I am unable to use it with dynamic. Here is the solution:

[ComVisible(true)]
public class Foo
{
    public void Bar(object o)
    {
        var dateTime = (DateTime)o.GetType().InvokeMember("getVarDate", BindingFlags.InvokeMethod, null, o, null);
        Console.WriteLine(dateTime);
    }
}

Comments

1

I found better solution for my project.

in javascript:

var date = new Date();
myComObject.DoSomething(date.getVarDate());

in C#

[ComVisible(true)]
public class Foo
{
    public void Bar(DateTime dateTime)
    {
        Console.WriteLine(dateTime);
    }
}

1 Comment

Of course it's possible, but I was wondering how to do that without calling getVarDate in javascript.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.