Use DateTime format in a class but restrict time tokens

288 Views Asked by At

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.

2

There are 2 best solutions below

8
On BEST ANSWER
DateTime d = new DateTime(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

var regex = new Regex("[yY]+|[M]+");
Console.WriteLine(regex.Replace("dd MM yy", m => d.ToString(m.Value)));
Console.WriteLine(regex.Replace("dd MMM yyyy HH mm tt", m => d.ToString(m.Value))); 

output

09 06 15
09 Jun 2015 00 00 AM
dd 06 15
dd Jun 2015 HH mm tt

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

2
On

I would overwrite the ToString([arg1]) and just call the base in the overload and beforehand filter arg1 and remove all that doesn't fit ur pattern.