jQuery UI Datepicker是否可以以与原始保存日期格式不同的格式显示日期?

问题描述 投票:0回答:1

我有一个设置了这种格式的Datepicker,并且与我页面上的文本框相关联(ASP MVC视图):

$(function () {
            $("#MyDateTextbox").datepicker({
                dateFormat: "dd-M-yy",
                showOn: "button",               
                buttonImage: "@Model.BaseURLOfSite" + "/Images/calendar.gif",
                buttonText: "Calendar"
            });
        });

如果文本字段本来是空的,并且我从控件中选择一个日期,并且该日期保存在指定的dateFormat中,则当我再次单击文本框时,日历将打开到保存的日期。例)“ 2020年12月31日”

但是,如果文本字段已经具有格式为“ 04/13/2020”的日期,则在我将选择器添加到页面之前,该值已保存到文本字段(和数据库)中。与文本框关联的日期选择器图标,或者页面被锁定,或者打开日期选择器并突出显示今天的日期。

使用datepicker控件设置并保存的新日期:没有问题。现有日期(采用不同格式),并由数据选择器控件访问:存在上述问题。

jquery jquery-ui datepicker jquery-ui-datepicker bootstrap-datepicker
1个回答
1
投票

[日期选择器中有一个beforeShow选项,我用于以下解决方案,可以是viewed here

为此,我将输入元素的现有值转换为datepicker可以解释的字符串,然后设置日期:

$(".datepicker").datepicker({
        dateFormat: "dd-M-yy",
        showOn: "button",               
        buttonText: "Calendar",
        beforeShow: function(ele, obj){

            // Current value
            var existing_date = $(ele).val();

            // If it contains a / then it's not formatted right
            if(existing_date.indexOf('/') > -1){

                // Using new Date and Date.parse gives us
                // Mon Apr 13 2020 00:00:00 GMT-0500 (Central Daylight Time)
                var new_date = new Date(Date.parse(existing_date));

                // Set the date
                $(ele).datepicker("setDate", new_date);

            }

        }
});

我不确定这是最好的方法,但这只是一个开始。希望对您有所帮助!

© www.soinside.com 2019 - 2024. All rights reserved.