4

I am using NCalc in a project. Is there a way to do date operations like

#16/02/2013# - #15/02/2013# = 1

I can't seem to be able to produce a result.

Expression.Evaluate();

Results is null for the above expression. I can compare two dates, but is there a way to do operations on them using NCalc?

Ionică Bizău
  • 109,027
  • 88
  • 289
  • 474
Daniel
  • 1,391
  • 2
  • 19
  • 40

4 Answers4

8

You can do this in ncalc quite easily if you are happy to create a custom function.

Expression e = new Expression("DayDiff(#16/02/2013#, #15/02/2013#)");
e.EvaluateFunction += delegate(string name, FunctionArgs args)
{
    if (name == "DayDiff")
    {
        var date1 = args.Parameters[0].Evaluate();
        var date2 = args.Parameters[1].Evaluate();
        var timespan = date2 - date1;
        return timespan.TotalDays; // double (you can convert to int if you wish a whole number!)
    }
}
Console.Write(e.Evaluate());
Chris Walsh
  • 3,423
  • 2
  • 42
  • 62
3

No, the NCalc library doesn't allow to do this.

Read this related topic.

But you can do it withoud of NCalc.

Assuming that a and b are of type DateTime, (a - b).TotalDays will return the number of days.

Ionică Bizău
  • 109,027
  • 88
  • 289
  • 474
  • Thanks, but I'll need NCalc as I need to provide expression editing options for the end user on a GUI. Your link was really useful. – Daniel Mar 27 '13 at 17:00
2

This is very late to the party but I have built an alternative option to NCalc called Expressive. This is available as a nuget package also.

It was originally built to match NCalcs functionality so migrating should require only a small amount of effort.

You can do a lot more date related functions:

DaysBetween(#15/02/2013#, #16/02/2013#)
Bijington
  • 3,661
  • 5
  • 35
  • 52
-1
    DateTime Date1, Date2;
    Date1 = DateTime.Parse("2013-03-27 8:42:00");
    Date2 = DateTime.Parse("2013-03-27 8:42:26");
    TimeSpan TimeSpan1 = Date2 - Date1;
    double DayDifference = TimeSpan1.TotalDays;
Michael Ross
  • 572
  • 4
  • 7