简体   繁体   中英

Parsing “DateTime.Now”?

I need to translate strings like this:

"DateTime.Now.AddDays(-7)"

into their equivalent expressions.

I'm only interested in the DateTime class. Is there anything built into .Net that'll help me do this, or do I just need to write my own little parser?

You can employ FLEE to do the expression parsing for you. The below code is tested and working in Silverlight (I believe in full C#, it may have a slightly different syntax around creating the expression, but it might work exactly like this anyway)

ExpressionContext context = new ExpressionContext();

//Tell FLEE to expect a DateTime result; if the expression evaluates otherwise, 
//throws an ExpressionCompileException when compiling the expression
context.Options.ResultType = typeof(DateTime);

//Instruct FLEE to expose the `DateTime` static members and have 
//them accessible via "DateTime".
//This mimics the same exact C# syntax to access `DateTime.Now`
context.Imports.AddType(typeof(DateTime), "DateTime");

//Parse the expression, naturally the string would come from your data source
IDynamicExpression expression = ExpressionFactory.CreateDynamic("DateTime.Now.AddDays(-7)", context);

//I believe there's a syntax in full C# that lets you evaluate this 
//with a generic flag, but in this build, I only have it return type 
//`Object` so we cast (it does return a `DateTime` though)
DateTime date = (DateTime)expression.Evaluate();

Console.WriteLine(date); //January 25th (7 days ago for me!)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM