Search code examples
c#datedatetimeteleriktelerik-datepicker

Unable to create date with current time from string


I am taking selected date from telerik date picker and want to take that selected date and current system time by 24 hours format and want date like this:

For Ex: Current Date = dd/mm/yy HH:Minutes:Seconds

21/1/2016 14:48:21

This is my code:

DateTime dt = DateTime.ParseExact(Datepicker1.SelectedDate.Value.ToShortDateString(), "dd/MM/yyyy", CultureInfo.InvariantCulture);//Error:String was not recognized as a valid DateTime.

Datepicker1.SelectedDate.Value= {1/21/2016 12:00:00 AM} 
Datepicker1.SelectedDate.Value.ToShortDateString()=1/21/2016 

Error:String was not recognized as a valid DateTime on Datetime.ParseExact.


Solution

  • Change your format in the ParseExact from

    "dd/MM/yyyy"
    

    to

    "M/d/yyyy" or "M/d/yyyy h:m:s tt" //the first one use .ToShortDateString(), the second one for 1/21/2016 12:00:00 AM
    

    The first one only takes care for case like 21/12/1997

    The second one takes care 12/21/1997, 2/21/1997, 12/2/1997, and 2/1/1997 in addition to take care of time info

    Also, note that you may consider to have multiple formats (just in case): "d/M/yyyy H:m:s", "d/M/yyyy h:m:s tt" to take care of the case where day and month are swapped and when you have AM/PM.

    MSDN link.