0

I have a string that I am getting from a Telerik DatePicker. The string I'm getting back is "Sat Aug 01 2009 00:00:00 GMT-0400 (Eastern Daylight Time)" I need to convert it to "yyyy-MM-dd" however I am having no luck. I keep the error "string was not recognized as a valid date time".

I've tried:

var fromDate = Convert.ToDateTime(dateFrom)

CultureInfo culture = new CultureInfo("en-US"); 
var fromDate = Convert.ToDateTime(dateFrom, culture);

var fromDate = DateTime.ParseExact(dateFrom, "yyyy-MM-dd", CultureInfo.InvariantCulture);

None of the above ways I have tried worked.

smuldr
  • 315
  • 1
  • 12
  • Does this answer your question? [Converting a String to DateTime](https://stackoverflow.com/questions/919244/converting-a-string-to-datetime) – Heretic Monkey May 01 '20 at 15:52
  • Never use `Convert.ToDateTime` to parse a string to a `DateTime`; just a bad idea all around. Use `DateTime.ParseExact` with a format string that matches the format of the date string you are receiving. Look at [Standard Date and Time Format Strings](https://learn.microsoft.com/en-us/dotnet/standard/base-types/standard-date-and-time-format-strings) and [Custom Date and Time Format Strings](https://learn.microsoft.com/en-us/dotnet/standard/base-types/custom-date-and-time-format-strings) for how to develop the appropriate string. – Heretic Monkey May 01 '20 at 15:55

2 Answers2

1

This should do the task

var date = DateTime.ParseExact(
    "Sat Aug 01 2009 00:00:00 GMT-0400 (Eastern Daylight Time)",
    "ddd MMM dd yyyy HH:mm:ss 'GMT-0400 (Eastern Daylight Time)'",
    CultureInfo.InvariantCulture);

var parsedDate = date.ToString("yyyy-MM-dd");       

The first argument of DateTime.ParseExact will be your string from Datepicker

var stringFromDatePicker =  "Sat Aug 01 2009 00:00:00 GMT-0400 (Eastern Daylight Time)";

var date = DateTime.ParseExact(stringFromDatePicker,
            "ddd MMM dd yyyy HH:mm:ss 'GMT-0400 (Eastern Daylight Time)'",
            CultureInfo.InvariantCulture);

var parsedDate = date.ToString("yyyy-MM-dd");
user8606929
  • 226
  • 1
  • 12
1

Building on user8606929 answer. If you are only interested in the date part of the string and not the time, then you could use substring to remove the end of the string before then parsing the string as a DateTime. Something along the lines of:

string dateFromDatePicker = "Sat Aug 01 2009 00:00:00 GMT-0400 (Eastern Daylight Time)";

string dateAsString = dateFromDatePicker.Substring(0,15);

DateTime selectedDate = DateTime.ParseExact(dateAsString, "ddd MMM dd yyyy", CultureInfo.InvariantCulture)

Also if you have any control over the code for the date picker you could look at the documentation for it to see if it is possible to change the format of the selected date, which might make it easier to parse/use.

PeterG
  • 143
  • 4