C# 如何在C语言中转换日期格式#

C# 如何在C语言中转换日期格式#,c#,C#,我需要将日期从 “2011年1月30日”->“2011年1月30日” 我怎样才能转换成c语言?我尝试了.Tostring(yyyy-MM-dd)。它不起作用。提前谢谢 您需要将字符串解析为DateTime类型,然后按照您想要的方式格式化它 以下是一段代码片段: string d = "01/30/2011"; DateTime dt = DateTime.Parse(s); string output = string.Format("{0:yyyy-MM-dd}",dt); 如果您的输入是字

我需要将日期从

“2011年1月30日”->“2011年1月30日”


我怎样才能转换成c语言?我尝试了.Tostring(yyyy-MM-dd)。它不起作用。提前谢谢

您需要将字符串解析为
DateTime
类型,然后按照您想要的方式格式化它

以下是一段代码片段:

string d = "01/30/2011";
DateTime dt = DateTime.Parse(s);
string output = string.Format("{0:yyyy-MM-dd}",dt);

如果您的输入是
字符串
(而不是
日期时间
),这就是您的
to字符串
调用不起作用的原因。您只需首先解析它,然后格式化结果值:

// I'll be honest: I don't really know if this is the "right" choice or not.
// Maybe someone else can weigh in on that.
IFormatProvider formatProvider = CultureInfo.InvariantCulture;

DateTime date = DateTime.ParseExact("01/30/2011", "MM/dd/yyyy", formatProvider);
string converted = date.ToString("yyyy-MM-dd");

这也是一个简单的示例:

private void button1_Click(object sender, EventArgs e)
{
     textBox1.Text = DateTime.Today.ToString("yyyy-MM-dd");
}

怎么搞的?错误格式错误?此外,您需要在格式周围加引号。或者,如果您不关心实际日期,您可以始终使用正则表达式。有没有具体原因说明为什么它会出现在单击按钮的事件中?
Console.WriteLine("{0:yyyy-MM-dd}", DateTime.Parse("01/30/2011"));