如何使用JavaScript计算两个asp文本框值并将其保存在数据库中?

时间:2017-01-03 14:34:10

标签: javascript asp.net datetimepicker

我有两个文本框,它们采用日期时间值,并且日期时间是从Bootstrap DateTimePicker设置的。现在我想使用JavaScript减去两个日期时间值并将其保存在数据库中?

这是我的日期时间选择器代码:

<script type="text/javascript">
        $(function () {
            $("#<%=datetimeCreated.ClientID %>").datetimepicker({
                calendarWeeks: true,
                useCurrent: false,
                format: 'YYYY-MM-DD HH:mm:ss',

            });

            $("#datetimeCreated").on('dp.change', function (e) {
                var date = $("#datetimeCreated").val();

            });

        });


        $(function () {
            $("#<%=datetimeClosed.ClientID%>").datetimepicker({
                calendarWeeks: true,
                format: 'YYYY-MM-DD HH:mm:ss',
            });

            $("#datetimeClosed").on('dp.change', function (e) {
                var date = $("#datetimeClosed").val();
            });
        });

1 个答案:

答案 0 :(得分:1)

您可以使用moment.js(这是datetimepicker已经需要)来计算差异,如下所示:

var diff = moment.duration(date1.diff(date2)).asDays();

详细了解文档中的https://jsfiddle.net/u49xmns3/.duration()

阅读代码,如果不清楚,请告诉我。

$(function () {
  $('#datetimepicker1, #datetimepicker2').datetimepicker();
  
  $('button').click(function(e) {
    e.preventDefault();
    var date1 = $('#datetimepicker1').data('DateTimePicker').date();
    var date2 = $('#datetimepicker2').data('DateTimePicker').date();
    var diff = moment.duration(date1.diff(date2)).asDays();
    // here is what are you looking for:
    console.log(diff);
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.44/css/bootstrap-datetimepicker-standalone.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.44/js/bootstrap-datetimepicker.min.js"></script>

<div class="container">
  <div class="row">
    <div class='col-sm-6'>
      <div class="form-group">
        <div class='input-group date' id='datetimepicker1'>
          <input type='text' class="form-control" />
          <span class="input-group-addon">
            <span class="glyphicon glyphicon-calendar"></span>
          </span>
        </div>
        <div class='input-group date' id='datetimepicker2'>
          <input type='text' class="form-control" />
          <span class="input-group-addon">
            <span class="glyphicon glyphicon-calendar"></span>
          </span>
        </div>
        <button class="btn btn-success">Submit</button>
      </div>
    </div>
  </div>
</div>