I am getting the date in DateTime format. e.g. 3/26/2015 12:00:00 AM I want to to convert it into Date Time (YYYY-MM-DD).
My output should be in DateTime :
DateTime obj = 2015-03-26
I tried,
string value = "11/12/2009";
IFormatProvider culture = new CultureInfo("en-US", true);
DateTime dateValue = DateTime.ParseExact(value, "yyyy-MM-dd", culture);
But for no avail.
Thanks in advance
You appear to be under the impression that a DateTime
has a format. It doesn't - no more than an int
is neither decimal, nor hex, nor binary - but could be converted to any of those textual representations.
It sounds like you should just use DateTime.Parse
for your incoming data (unless you know the exact format to expect, in which case specify that), keep the result as a DateTime
for as long as you can, and then use ToString
with a custom format string to format it when you need to. (Don't convert it into text until you do need to though... Avoid conversions as much as you can, as each one is a potential source of errors.)
DateTime date = DateTime.Parse(value, culture);
...
// Lots of other code
...
string isoDate = date.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
See more on this question at Stackoverflow