我想将日期时间数据存储到SQL Server数据库中。我刚创建了两个用于插入日期和时间的输入字段,然后将其添加为字符串,然后将此字符串转换为c#datetime格式。我的代码
myView文件
<div class="editor-field">
<!-- for insert date -->
<input type="text" name="tantativeDate" id="tantativeDate" class="datefield">
<!-- for insert time -->
<input type="time" name="tantativeTime" id="tantativeTime" />
</div>
<div class="editor-field">
<!-- for insert date -->
<input type="text" name="dateArrival" id="dateArrival" class="datefield" />
<!-- for insert time -->
<input type="time" name="timeArrival" id="timeArrival" />
</div>
我的控制器方法:
public ActionResult DemoMethod()
{
// get date and time and add this
string tan = (string)Request["tantativeDate"] + " " + (string)Request["tantativeTime"];
// get date and time and add this
string arrive = (string)Request["dateArrival"] + " " + (string)Request["timeArrival"];
// convert datetime string into date time format
DateTime dt = DateTime.Parse(tan, System.Globalization.CultureInfo.CurrentCulture);
// convert datetime string into date time format
DateTime dy = DateTime.Parse(arrive, System.Globalization.CultureInfo.CurrentCulture);
// save data into database
DemoModel demo = new DemoModel()
{
demo.tantativeTime = dt;
demo.timeArrival = dy;
};
db.demo.Add(demo);
db.SaveChange();
}
我收到了以下错误:
将datetime2数据类型转换为日期时间数据类型会导致超出范围的值。
答案 0 :(得分:0)
您的代码似乎没有错误,可能您可能有另一个日期时间字段,该字段可能为空,请尝试解决此问题。如果仍有问题,则显示您的型号代码。