如何解决问题从datepicker获取日期1970-01-01?

时间:2020-04-01 02:21:34

标签: javascript jquery html datepicker

我正在使用日期选择器和功能。该功能是使用从dd-mm-yyyyyyyy-mm-dd样式的转换。目前,我已经在数据库中记录了日期,数据库格式为yyyy-mm-dd,所以我需要先转换为dd-mm-yyyy样式以便于阅读。因此,在提交过程中,我需要转换回yyyy-mm-dd(这里使用函数)。

我打开了一个表格,该表格已经记录了从数据库读取的内容,包括日期,例如,日期为26-03-2020。因此,我尝试提交表单而不更改日期。问题来了,日期设置为1970-01-01,为什么会发生这种情况?见下文。

我正在使用此bootstrap-datepicker

我在下面都尝试过,但这是我得到的:

var actualDate = $('#actualDate').val(); // If i try this I will get NaN-NaN-NaN

var actualDate = $('#actualDate').datepicker('getDate'); // If i try this I will get 1970-01-01

enter image description here

enter image description here

HTML

<input type="text" class="form-control" id="actualDate"></input>

JS

$.ajax({
    url : url_projectList + '/1st_api',
    crossDomain: true,
    type : 'POST',
    dataType : 'json',
    data: JSON.stringify({project_id: id}),
    success: function(response){

        var actualDate = $('#actualDate').val();       // If i try this I will get NaN-NaN-NaN
        var actualDate = $('#actualDate').datepicker('getDate');     // If i try this I will get 1970-01-01

        if ($("#actualDate").val() == ""){
            var project_start_date = null;  // This is working fine
        } else {
            project_start_date = sendDate(actualDate);   // Here is the error coming
        }

        console.log(project_start_date)  // I got NaN-NaN-NaN

        $.ajax({
            url : url_projectList + '/2nd_api',
            type : 'POST',
            dataType : 'json',
            data: params,
        });
    }
});

function sendDate(input_date){

    proc_date = new Date(input_date)
    year = proc_date.getYear() + 1900
    month = proc_date.getMonth() + 1
    day = proc_date.getDate()

    if (month < 10)
    {
      month = "0" + month;
    }
    if (day < 10)
    {
      day = "0" + day;
    }

    return year +"-"+ month +"-"+ day;
}

DATEPICKER

$('#actualDate').datepicker({
    language: 'en',
    format: "dd-mm-yyyy",
    clearButton: true,
    toggleSelected: true,
    autoclose: true,
    todayHighlight: true,
    ignoreReadonly: true,
});

1 个答案:

答案 0 :(得分:0)

您应该更改数据选择器的格式

$('.datepicker').datepicker({
    format: 'yyyy/dd/mm'
});

有关更多信息,请访问

https://bootstrap-datepicker.readthedocs.io/en/stable/

相关问题