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

New Post: Date marshalling

0
0
Hi Thomas,

In general, ClearScript favors seamless access over data conversion. We believe that this approach maximizes flexibility. There are exceptions, of course. If ClearScript didn't convert strings and numbers, for example, using it would be very painful :)

Instead of converting JavaScript dates to DateTime structures, ClearScript makes it easy for hosts to use JavaScript dates directly and convert them to DateTime structures if necessary:
dynamic date = engine.Evaluate("new Date()");
Console.WriteLine(date.toString());

var dateTime = new DateTime(
    date.getFullYear(),
    date.getMonth() + 1,
    date.getDate(),
    date.getHours(),
    date.getMinutes(),
    date.getSeconds(),
    date.getMilliseconds()
);
Console.WriteLine(dateTime);
ClearScript also makes it easy to deal with DateTime structures in script code:
engine.AddHostType("DateTime", typeof(DateTime));
engine.AddHostType("Console", typeof(Console));
engine.Execute(@"
    var dateTime = DateTime.Now;
    Console.WriteLine(dateTime);

    var date = new Date(0);
    date.setFullYear(dateTime.Year, dateTime.Month - 1, dateTime.Day);
    date.setHours(dateTime.Hour, dateTime.Minute, dateTime.Second, dateTime.Millisecond);
    Console.WriteLine(date.toString());
");
You could of course come up with more efficient conversion routines, but this is just an example.

Good luck!

Viewing all articles
Browse latest Browse all 2297