转换字符串类型日期类型

时间:2018-02-10 08:15:02

标签: javascript jquery html

我有一个带有bootstrap datepicker的两个输入字段。

$('#from').datepicker({
  format: "dd-mm-yyyy",
  autoclose: true
});
$('#to').datepicker({
  format: "dd-mm-yyyy",
  autoclose: true
});

$("form").submit(function(event) {
    event.preventDefault();
    var date1 = $("#from").val();
    var date2 = $("#to").val();
    if (date2 < date1) {
      console.log(new Date(d1));
      $("#dateerror").html('<div class="alert alert-danger alert-dismissable"><a 
        href = "#"
        class = "close"
        data - dismiss = "alert"
        aria - label = "close" > & times; < /a> <
        strong > Opps! < /strong> Invalid Dates</div > ');

        $("input[type=text]").val("");
      }
    });
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" placeholder="start date" class="form-control" id="from" name="from" required>
<input type="text" placeholder="end date" class="form-control" id="to" name="to" required>

变量date1和date2来自输入字段。当我将date1与date2进行比较时,我无法获得正确的输出。如何将date1和date2转换为日期格式以进行比较?

3 个答案:

答案 0 :(得分:2)

var myDate = new Date("February 19, 2018")

或在你的情况下:

var date1 = new Date($("#from").val())
var date2= new Date($("#to").val())

在此处阅读更多内容:https://docs.microsoft.com/en-us/scripting/javascript/date-and-time-strings-javascript

答案 1 :(得分:2)

使用datepicker的getDate()方法:

var date1 = $("#from").datepicker("getDate");
var date2 = $("#to").datepicker("getDate");

答案 2 :(得分:0)

&#13;
&#13;
var yy = Date.parse("February 19, 2018");

var xx = Date.parse("March 21, 2012");

var timeDiff = Math.abs(xx - yy);
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24)); 
console.log(diffDays)
var message="xx is small";
if (yy< xx) {
 message="yy is small";
 }
console.log(message)
&#13;
&#13;
&#13;

我建议您最好使用moment.js来获得更多内置功能。