-1

I am trying to compute the string expression by DataTable.Compute.

A simple string like below is working:

        static void Compare()
        {
            var logicalExpression = "'2022-09-14' <= '2029-12-31'";
            DataTable dt = new DataTable();
            var result = (bool)dt.Compute(logicalExpression, "");
        }

But, the date 2022-09-14 is dynamic, it should be the date for now.

I have tried to replace '2022-09-14' with Now(),GETDATE(). None of them work.

Is there any function to get current date time in Compute?

Edward
  • 28,296
  • 11
  • 76
  • 121

2 Answers2

0

You can do this like this:

var logicalExpression = "'" + DateTime.Now.ToShortDateString() + "' <= '2029-12-31'";

you can also specify in what format you want the date, see this post for an example.

Dmyto Holota
  • 356
  • 1
  • 4
  • 14
  • You can't choose the format and this code won't work unless "yyyy-MM-dd" is the default format for the local machine. You need to either hard-code "yyyy-MM-dd" and then do a text comparison or hard-code "MM/dd/yyyy" and do a proper date comparison. Any other format will not work. – John Sep 14 '22 at 09:57
  • For `DateTime.Now`, it is in C# complier file, I need to use the function which is in string format and can be calculate in `Compute` directly. – Edward Sep 15 '22 at 00:41
0
var logicalExpression = $"#{DateTime.Now:MM/dd/yyyy}# <= #12/31/2029#";

This is the proper way to represent dates in this context. See here for more information.

John
  • 3,057
  • 1
  • 4
  • 10
  • For `DateTime.Now`, it is in C# complier file, I need to use the function which is in string format and can be calculate in `Compute` directly. – Edward Sep 15 '22 at 00:41
  • @Edward, no you don't. `Compute` requires you to pass it a `string` as an argument. That `string` can be constructed in any way you like. Doing exactly as I have demonstrated will produce the exact same result as if you were to use a function within the `string`. Of course, there is no such function anyway, which you'd know if you had bothered to read the documentation, so you have no choice but to do it the way I've shown. The only reason this could be an issue is if you wanted to create the `string` once and then use it multiple times at different times. Just don't do that. – John Sep 15 '22 at 00:55