Click here to Skip to main content
15,887,083 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
how to convert string into date format?

What I have tried:

public ActionResult SaveSelectedCustomers(string GetDateTime)
        {
            try
            {
                DateTime getDateTime = DateTime.ParseExact(GetDateTime, "yyyyMMdd HH:mm", CultureInfo.InvariantCulture);
                return Json(true);     
            }
            catch( Exception ex)
            {
                throw ex;
            }
        }



it throws following error:-
An exception of type 'System.FormatException' occurred in oMail.Web.dll but was not handled in user code

Additional information: String was not recognized as a valid DateTime.
Posted
Updated 21-May-17 20:51pm
Comments
Maciej Los 22-May-17 2:33am    
Are you sure that string is in that format: "yyyyMMdd"?
Shridhar Salunkhe 22-May-17 2:41am    
dateFormat: "dd-mm-yy" in jquery
Maciej Los 22-May-17 2:46am    
So, change the line where you convert string to date to: DateTime getDateTime = DateTime.ParseExact(GetDateTime, "dd-MM-yy", CultureInfo.InvariantCulture);
Shridhar Salunkhe 22-May-17 2:51am    
and for time?
Shridhar Salunkhe 22-May-17 2:53am    
not working

1 solution

Maciej Los wrote:

Are you sure that string is in that format: "yyyyMMdd"?
Shridhar Salunkhe wrote:

dateFormat: "dd-mm-yy" in jquery



DateTime.ParseExact Method (String, String, IFormatProvider) (System)[^] expects a exact string representation of a date, which must be in the format defined by the format parameter. If there's a time part, you have to define it.

[EDIT]
In case you have a date format like this: Mon May 22 2017 12:48:00 GMT+0530, you have to use DateTimeOffset.ParseExact Method (String, String, IFormatProvider) (System)[^] instead of DateTime.Parse method.
See: C# string to DateTime with timezone - Stack Overflow[^]
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900