Change DateTime Format as "yyyy-mm-dd"

c#, datetime, string

Solution

From `DateTime.ParseExact`

Converts the specified string representation of a date and time to its DateTime equivalent using the specified format and culture-specific format information. The format of the string representation must match the specified format exactly.

In your case, they are not.

You can use `dd/M/yyyy hh:mm:ss tt` format instead. Here an example;

string s = "13/5/2014 12:00:00 AM";
var date = DateTime.ParseExact(s, "dd/M/yyyy hh:mm:ss tt",
                                   CultureInfo.InvariantCulture);
Console.WriteLine(date);

`DateTime` has no implicit format, it is just a `DateTime` value. You can format it as `string` with `DateTime.ToString()` method like;

date.ToString("yyyy-M-dd hh:mm:ss");

Take a look at;

- Custom Date and Time Format Strings

Problem

This function is working fine but I return dd-MM-yyyy format but I want yyyy-MM-dd format My input value is '13/5/2014 12:00:00 AM' I need change this format as '2014-5-13 00:00:00' but all the datetime variable is return in dd-mm-yyyy format I don't want to convert the date as string I want to store date value in datetime property with 'yyyy-MM-dd' format: ``` public DateTime DateConvertion(string Input) { DateTime DateValue = DateTime.ParseExact(Input, "dd-MM-yyyy", CultureInfo.InvariantCulture); return DateValue; } ```

Original source