首页 > 解决方案 > 如何解决从 datepicker 获取日期 1970-01-01 的问题?

问题描述

我正在使用日期选择器和函数。功能是使用convert from dd-mm-yyyyto yyyy-mm-ddstyle。目前情况我已经在数据库中记录了日期,数据库格式yyyy-mm-dd所以我需要先转换为dd-mm-yyyy样式以便于阅读。所以在提交期间我需要转换回yyyy-mm-dd(这里我使用该函数)。

我打开了一个已经记录了从数据库读取的表格,包括日期,例如日期是26-03-2020. 所以我尝试在不更改日期的情况下提交表格。问题出现在这里,日期设置为1970-01-01,为什么会发生这种情况?见下文。

我正在使用这个引导日期选择器

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

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

在此处输入图像描述

在此处输入图像描述

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

日期选择器

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

标签: javascriptjqueryhtmldatepicker

解决方案


你应该改变数据选择器的格式

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

欲了解更多信息,请访问

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


推荐阅读