在 class 中使用 DateTime 格式但限制时间标记

Use DateTime format in a class but restrict time tokens

我有一个特殊的问题要解决。我写了一个 MonthYear class,它本质上在幕后维护一个 DateTime 对象,并且只允许 methods/properties 用于 DateTime 的月份和年份部分。一切正常。

现在我还有一个要求。我想允许任何使用我的 class 的人使用日期标记来使用 ToString 方法,但我只想格式化 month/year 标记,即 M、MM、MMM、MMMM、y、yy、yyy , yyyy, yyyyy 并将 m 或 t 等其他标记视为文字。

有没有可能不写我自己的东西就可以做这样的事情parser/tokenizer?

编辑:我想我的问题有点难以理解。

这是一个更简单的表格。假设我扩展了 DateTime class 并且我想重写 ToString 方法以获得以下输出:

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

我想忽略除了我上面提到的那些之外的所有标记。我希望这有助于使问题更简单。

我不需要帮助编写只允许上述标记的解析器方法。我只需要知道有没有一种方法可以通过内置的东西来完成。

我会覆盖 ToString([arg1]) 并在重载中调用基础并预先过滤 arg1 并删除所有不符合您的模式的内容。

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))); 

输出

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

正则表达式仅用于在格式字符串中查找 month/year 格式。匹配用于格式化日期时间和格式化结果替换格式字符串的一部分