简体   繁体   English

无法将DateTime格式从MM / dd / yyyy转换为yyyy-MM-dd

[英]Can't convert DateTime format from MM/dd/yyyy to yyyy-MM-dd

I know this is a recurrent question but I cannot seem to be able to get this to work even after a lot of research! 我知道这是一个经常出现的问题,但是即使经过大量研究,我似乎也无法使它正常工作! I want to convert a string to a DateTime. 我想将字符串转换为DateTime。

public DateTime ConvertToDateTime(string thisDate)
{
    return DateTime.ParseExact(thisDate, "yyyy-MM-dd", CultureInfo.InvariantCulture);
}

(EDITED) (编辑)

I give "2012-03-07" as a parameter and I get a DateTime that is 03/07/2012 12:00AM . 我给"2012-03-07"作为参数,并且我得到的DateTime03/07/2012 12:00AM When I wanted it to return: 2012-03-07 00:00:00 当我希望它返回时: 2012-03-07 00:00:00

Your code is correct; 您的代码是正确的; your expectations are wrong. 您的期望是错误的。

When a method returns a DateTime , it has no format . 当方法返回DateTime它没有格式 Well, more accurately, it has a binary in-memory format that has no relation to its string format. 好吧,更准确地说,它具有二进制的内存格式,与它的字符串格式无关。

The debugger formats the DateTime to show it to you, but that has no bearing on the DateTime value itself. 调试器将格式化DateTime以显示给您,但这与DateTime值本身无关。 The format it uses is presumably determined by your locale settings. 它使用的格式大概由您的区域设置确定。

When you want to display the DateTime to a user, or pass it as a string to some other function, you can format it as you like using one of the ToString overloads. 当您要向用户显示DateTime或将其作为字符串传递给其他函数时,可以使用ToString重载之一随意设置其格式。

It may be that you are displaying or passing the return value of the function you've given; 可能是您正在显示或传递给定函数的返回值。 if so, the error is in the code displaying or passing the DateTime, not in the function you've given. 如果是这样,则错误在于显示或传递DateTime的代码中,而不在于您提供的函数中。 If that's the case, edit your answer to include that code, and perhaps we can help you fix it. 如果是这种情况,请编辑您的答案以包含该代码,也许我们可以帮助您修复它。

Try this 尝试这个

public String ConvertToDateTime(string thisDate)
{
    return DateTime.ParseExact(thisDate, "yyyy-MM-dd",
           CultureInfo.InvariantCulture).toString("yyyy-MM-dd");
}

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

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