我正在尝试从网址获取日期(& datetime),然后在将其存储到数据库之前将其转换为正确的格式。
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:
startDateTime
var reqDateTime = Request.QueryString["startDateTime"];
timingRequest.IgnoreEntry = DateTime.ParseExact(reqDateTime, "dd/MM/yyyy hh:mm tt", CultureInfo.InvariantCulture);
答案 0 :(得分:1)
在您的第一个场景中,阅读indexOf(" ")
后无需添加+1。 +1添加额外的空间
//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*/
正确的方法是s.Substring(0, s.IndexOf(" "))
在第二种情况下,请使用HH:mm:ss
之类的日期格式,而不是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);
优雅的方法是:
@Credit Stephen Muecke
查看您的网址后,您可以编写一个方法,例如
public ActionResult Create(int empId, int attID, DateTime startDate, DateTime startDateTime)
{
/*Do your work here, DefaultModelBinder will take care of parameters*/
}
答案 1 :(得分:0)
第一个示例修复:
var reqDate = Request.QueryString["StartDate"];
reqDate = reqDate.Substring(0, reqDate.IndexOf(" "));
timingRequest.ReqDate = DateTime.ParseExact(reqDate, "MM/dd/yyyy", CultureInfo.InvariantCulture);
第二个示例修复:
var reqDateTime = Request.QueryString["startDateTime"];
timingRequest.IgnoreEntry = DateTime.ParseExact(reqDateTime, "dd/MM/yyyy HH:mm:ss", CultureInfo.InvariantCulture);