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?

prostynick
  • 6,129
  • 4
  • 37
  • 61

3 Answers3

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);
Frédéric Hamidi
  • 258,201
  • 41
  • 486
  • 479
  • 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. – prostynick Apr 18 '11 at 09:36
  • There are no "Javascript Date objects" in C# – Magnus Apr 18 '11 at 09:48
  • 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. – prostynick Apr 18 '11 at 11:19
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);
    }
}
prostynick
  • 6,129
  • 4
  • 37
  • 61
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);
    }
}
slugster
  • 49,403
  • 14
  • 95
  • 145
Mentor
  • 11
  • 1