C# – Convert DateTime format yyyy-MM-dd


I am trying to change the DateTime format from "dd/MM/yyyy" to "yyyy-MM-dd"

This is what I have at the moment:

DateTime date = Convert.ToDateTime("31/01/2000");

String format = "yyyy-MM-dd";
String dateStr = date.ToString(format);

DateTime parsedDate = DateTime.ParseExact(dateStr, format, CultureInfo.InvariantCulture);

I get these results:

31/01/2000 12:00:00 AM
31/01/2000 12:00:00 AM

Ultimately, I want the last result to be 2000-01-31

EDIT: Just to clarify my actual objective. I am using SSIS to convert a DT_DATE(dd/MM/yyyy) field into another DT_DATE(yyyy-MM-dd) field. So thought I would use a Script Component.
This means I can't convert it back into a String.


Sorry everyone, I think I've muddled up the question, but I can answer it myself now.

My goal was to convert source field DT_DATE(dd/MM/yyyy) into dest field DT_DATE(yyyy-MM-dd) in SSIS.

I first tried using a Derived Column by 'Replacing the original field' with (DT_DBDATE)field. This didn't work as it gave me the original source.

So I tried using a Script Component which led to the top part of my question, and lots of confusion. It simply didn't work.

The solution was to use a Derived Column by 'Adding a new column' and giving it (DT_DBDATE)field. DT_DBDATE's original format is in fact yyyy-MM-dd.

Best Solution

I think you just need to know about the ToString overloads:

string fromFormat = "dd/MM/yyyy"; 
string toFormat = "yyyy-MM-dd";

DateTime newDate = DateTime.ParseExact("15/01/2001", fromFormat, null);