0

I want to store datetime data into SQL Server database. I just created two input fields for inserting date and time, then add this as a string and next convert this string into the c# datetime format. My code

myView file

 <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>

my Controller method:

  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();
}

And I have fetched the following error:

The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
sabbir
  • 19
  • 8

1 Answers1

0

your code seems no error, probably you may have another datetime field which may be empty, try to fix this. If still a problem then shows your model code.

sabbir
  • 2,020
  • 3
  • 26
  • 48