简体   繁体   English

如何将日期格式从 DD/MM/YYYY 或 MM/DD/YYYY 更改为 YYYY-MM-DD?

[英]How to change date format from DD/MM/YYYY or MM/DD/YYYY to YYYY-MM-DD?

i need to change the format of my date string using C#我需要使用 C# 更改日期字符串的格式

from : "06/16/2010"or "16/06/2010"来自:“06/16/2010”或“16/06/2010”

to : "2010-06-16"至:“2010-06-16”

can you please help me achieve this你能帮我实现这个吗

thanks谢谢

If you already have it as a DateTime , use:如果您已经将其作为DateTime ,请使用:

string x = dt.ToString("yyyy-MM-dd");

See the MSDN documentation for more details.有关更多详细信息,请参阅MSDN 文档 You can specify CultureInfo.InvariantCulture to enforce the use of Western digits etc. This is more important if you're using MMM for the month name and similar things, but it wouldn't be a bad idea to make it explicit:您可以指定CultureInfo.InvariantCulture来强制使用西方数字等。如果您使用 MMM 作为月份名称和类似的东西,这一点更为重要,但明确表示也不错:

string x = dt.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);

If you have a string to start with, you'll need to parse it and then reformat... of course, that means you need to know the format of the original string.如果你有一个字符串开始,你需要解析它然后重新格式化......当然,这意味着你需要知道原始字符串的格式。

下面会做。

string datestring = DateTime.Now.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
String dt = Date.Now.ToString("yyyy-MM-dd");

现在你为 dt 得到了这个,2010-09-09

We can do something like this我们可以做这样的事情

DateTime date_temp_from = DateTime.Parse(from.Value); //from.value" is input by user (dd/MM/yyyy)
DateTime date_temp_to = DateTime.Parse(to.Value); //to.value" is input by user (dd/MM/yyyy)

string date_from = date_temp_from.ToString("yyyy/MM/dd HH:mm");
string date_to = date_temp_to.ToString("yyyy/MM/dd HH:mm");

Thank you谢谢

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM