简体   繁体   中英

DateTime.ParseExact: String was not recognized as a valid DateTime

I am trying to get the date (& datetime) from the url and then convert it into its proper format before storing it in the db.

var reqDate = Request.QueryString["StartDate"];

//at this point I have reqDate: 05/15/2018 00:00:00
reqDate = reqDate.Substring(0, reqDate.IndexOf(" ") + 1);

//after stripping off the time part I have: 05/15/2018 
timingRequest.ReqDate = DateTime.ParseExact(reqDate, "MM/dd/yyyy", CultureInfo.InvariantCulture);

//but this throws the exception

URL:

在此处输入图片说明

Same is the case with startDateTime

var reqDateTime = Request.QueryString["startDateTime"];
 timingRequest.IgnoreEntry = DateTime.ParseExact(reqDateTime, "dd/MM/yyyy  hh:mm tt", CultureInfo.InvariantCulture);

In your first scenario, No need to add +1 after reading indexOf(" ") . +1 adding extra space to date

//Lets take date in string is "05/15/2018 00:00:00"
Console.WriteLine(s.Substring(0, reqDate.IndexOf(" ")+1)); /*This will print "05/15/2018 " WITH EXTRA SPACE*/

Correct way is s.Substring(0, s.IndexOf(" "))

In second scenario, use date format like HH:mm:ss instead of HH:mm tt

//Here use "hh:mm:ss" instead of "hh:mm tt"
DateTime dateTime = DateTime.ParseExact(reqDateTime, "dd/MM/yyyy  hh:mm:ss", CultureInfo.InvariantCulture);

Elegant approach would be:

@Credit Stephen Muecke

After looking at your URL, you can write a method having parameters like,

public ActionResult Create(int empId, int attID, DateTime startDate, DateTime startDateTime)
{
 /*Do your work here, DefaultModelBinder will take care of parameters*/
}

First Example fix:

var reqDate = Request.QueryString["StartDate"];
reqDate = reqDate.Substring(0, reqDate.IndexOf(" "));

timingRequest.ReqDate = DateTime.ParseExact(reqDate, "MM/dd/yyyy", CultureInfo.InvariantCulture);

Second Example Fix:

var reqDateTime = Request.QueryString["startDateTime"];
 timingRequest.IgnoreEntry = DateTime.ParseExact(reqDateTime, "dd/MM/yyyy HH:mm:ss", CultureInfo.InvariantCulture);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM