m和mm在c#日期格式字符串中的核心区别在于是否保留前导零:m会省略月份的前导零(如1月显示为"1"),而mm始终强制显示两位数字(如1月显示为"01")。

ToString("M")与ToString("MM")的格式化差异是什么?
使用DateTime.ToString()方法时,传入不同的格式字符串会得到不同长度的月份表示。当使用M时,如果月份是个位数,生成的字符串长度会减少;当使用MM时,无论月份是多少,结果总是固定两位。这种差异在处理需要固定宽度输出的场景(如文件名或数据库字段)时非常关键。

using System;
class Program
{
static void Main()
{
DateTime date = new DateTime(2023, 1, 15);
Console.WriteLine(date.ToString("M"));
Console.WriteLine(date.ToString("MM"));
}
}
ParseExact解析时如何处理这两种格式?
在使用DateTime.ParseExact进行反向解析时,格式字符串必须与输入字符串的形态严格匹配。如果输入是"1/15/2023",则必须使用M/d/yyyy;如果输入是"01/15/2023",则必须使用MM/dd/yyyy。如果格式不匹配,解析将抛出异常。

using System;
using System.Globalization;
class Program
{
static void Main()
{
string input1 = "1/15/2023";
string input2 = "01/15/2023";
try
{
DateTime d1 = DateTime.ParseExact(input1, "M/d/yyyy", CultureInfo.InvariantCulture);
Console.WriteLine(d1); // 成功
}
catch (FormatException)
{
Console.WriteLine("Format mismatch for input1");
}
try
{
DateTime d2 = DateTime.ParseExact(input2, "MM/dd/yyyy", CultureInfo.InvariantCulture);
Console.WriteLine(d2); // 成功
}
catch (FormatException)
{
Console.WriteLine("Format mismatch for input2");
}
}
}
当月份为12时,M和MM的输出表现如何?
当月份为两位数(即10月至12月)时,M和MM的输出结果是相同的,都会显示为两位数字。例如,对于12月,两者都输出"12"。只有在月份为1至9时,两者的差异才会显现,M输出单字符,MM输出双字符。











