I have a peculiar problem I want to solve. I have written a MonthYear
class which essentially maintains a DateTime
object behind the scenes and only allows methods/properties for month and year portion of the DateTime
. Everything is working fine.
Now I have another requirement. I want to allow anyone using my class to use ToString
method using date tokens but I want to only format the month/year tokens i.e. M, MM, MMM, MMMM, y, yy, yyy, yyyy, yyyyy and treat other tokens like m or t as literals.
Is it possible to do such a thing without writing my own parser/tokenizer?
EDIT: My Question is a bit difficult to understand I guess.
Here is a simpler form. Suppose I extend the DateTime
class and I want to override ToString
method in such a way that it gets me the following output:
DateTimeEx d = new DateTimeEx(2015, 6, 9);
Console.WriteLine(d.ToString("dd MM yy")); // dd 06 15
Console.WriteLine(d.ToString("dd MMM yyyy HH mm tt")); // dd Jun 2015 HH mm tt
I want to ignore every token except the ones I mentioned above. I hope this helps in making the question simpler.
I don't need help writing a parser method which only allows the above mentioned tokens. I only need to know is there a way this can be done with something built in.
output
a regex is used to find only the month/year format in format string. matches are used to format a datetime and result of formatting replaces a part of format string