How to get date in specific format

僤鯓⒐⒋嵵緔 提交于 2019-12-25 04:09:02

问题


I want to have the dateformat in this format: 2015-08-04T00:00:00Z.

so first year, month, day.

 beforeShowDay: function (date) {
                                var dt = $.datepicker.formatDate('yy-mm-dd', date, "getDate")                               
                                return [$('#form_one3 > option:gt(0)[value="' + dt + 'T00:00:00Z"]').length != 0];

                            },


                            onSelect: function (dateText, inst) {
                                var dt = $.datepicker.formatDate('yy-mm-dd', dateText, "getDate")
                                alert(dt);

                                var hallo = $("#form_inp1").val() + 'T00:00:00Z';
                                alert(dateText);
                                alert(hallo);


                                //$("#form_inp1").datepicker("getDate");
                                //alert($("#form_inp1").formatDate('yy-mm-dd', dateText, "getDate")


                            },

But If I do an alert(dateText) I see the format as: 4-8-2015 and it has to be: 2015-08-04.

Thank you

If I try it like this:

onSelect: function (dateText, inst) {
                                dateText = dateText.split("-");
                                dateText = new Date('' + dateText[2] + '-' + dateText[1] + '-' + dateText[0] + '');
                                alert(dateText);
}

I get invalid date

So this var hallo = $("#form_inp1").val() + 'T00:00:00Z';

returns: 4-8-2015T00:00:00Z . But it has to be:2015-08-04T00:00:00Z.

Thank you


回答1:


Quick fix is to change the date format using plain Javascript. This can be achieved by following script.

dt= dt.split("-");
dt = new Date('' + dt[2] + '-' + dt[1] + '-' + dt[0] + '');

to add zero in case the day, month and year is below 10, use following method.

function AddTrailingZero(i) {
    if (i < 10) { i = "0" + i };  // add zero in front of numbers < 10
    return i;
}

Let me know if you have any question related to the code snippet above.



来源:https://stackoverflow.com/questions/31649537/how-to-get-date-in-specific-format

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!