如何在js中将日期字符串转换为日期格式

时间:2018-06-29 08:55:13

标签: javascript

注意:START_DATE和END_DATE为字符串格式,字符串格式为:“ 29-06-2018 14:11”

我想将START_DATE和END_DATE转换为日期格式。

 function checkConstraints2() {
        debugger
        var currentyear = document.getElementById('START_DATE').value;
        var builtYear = document.getElementById('END_DATE').value;
        var dif = currentyear < builtYear
        if (dif) {
            document.getElementById("validationBuiltyaer2").style.display = "none";
            return true;
        }
        else {
            document.getElementById("validationBuiltyaer2").style.display = "block";
            document.getElementById("validationBuiltyaer2").innerText = "End Date Should be Greater Than From Date";
            flag = false;
        }
    }

2 个答案:

答案 0 :(得分:0)

在这里,您可以使用moment来解析日期字符串-

var dateString = "29-06-2018 14:11";

console.log(moment(dateString, "DD-MM-YYYY HH:mm"));

var startDateString = "29-06-2018 14:11";
var endDateString = "30-06-2018 14:11";

var startDate = moment(startDateString, "DD-MM-YYYY HH:mm");
var endDate = moment(endDateString, "DD-MM-YYYY HH:mm");

console.log(startDate < endDate);
<script src="https://momentjs.com/downloads/moment.min.js"></script>

答案 1 :(得分:0)

尝试一下:

var parts = '29-06-2018 14:11'.split(' ')[0].split('-');
// Please substract 1 from month part as javaScript counts months from 0:
// January - 0, February - 1, etc.
var mydate = new Date(parts[2], parts[1] - 1, parts[0]);