简体   繁体   中英

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.

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 . When I wanted it to return: 2012-03-07 00:00:00

Your code is correct; your expectations are wrong.

When a method returns a DateTime , it has no format . 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. 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.

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. 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");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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