Click here to Skip to main content
13,797,500 members
Rate this:
Please Sign up or sign in to vote.
how to convert string into date format?

What I have tried:

public ActionResult SaveSelectedCustomers(string GetDateTime)
                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 21-May-17 21:29pm
Updated 21-May-17 21:51pm
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
Maciej Los 22-May-17 2:57am
As i mentioned in the answer to your question, you have to provide exact date and time format! Follow the link to get more info.
Shridhar Salunkhe 22-May-17 3:20am
string:- Mon May 22 2017 12:48:00 GMT+0530 (India Standard Time)
this string i m getting from jquery
Maciej Los 22-May-17 3:48am
See updated answer.

1 solution

Rate this: bad
Please Sign up or sign in to vote.

Solution 1

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.

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[^]

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

  Print Answers RSS
Top Experts
Last 24hrsThis month

Advertise | Privacy | Cookies | Terms of Service
Web04 | 2.8.181207.3 | Last Updated 22 May 2017
Copyright © CodeProject, 1999-2018
All Rights Reserved.
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100