0

Is there a relatively straightforward way to do a date comparison, using jquery, on a UK formatted date? I'm trying to check if the number of days selected via a date input field is greater than or equal to a set number. Unfortunately I can't change the date format and need to work with dd/mm/yy.

UPDATE: the date I am working with is already in UK format dd/mm/yy - I am trying to convert this into a format which can be compared with the current date, to find number of days elapsed.

Working solution:

function checkDaysElapsed (input) {

                var datePart = input.split("/");
                year = datePart[2]; // get only two digits
                month = datePart[1]; 
                day = datePart[0];

                var date1 = new Date(year,month-1,day); 

                var currentTime = new Date();
                var month2 = currentTime.getMonth();
                var day2 = currentTime.getDate();
                var year2 = currentTime.getFullYear();
                var date2 = new Date(year2,month2,day2);
                console.log(year + '/' + month + '/' + day);
                console.log(year2 + '/' + month2 + '/' + day2);

                delta = date2 - date1; 
                // delta is the difference in milliseconds 
                delta_in_days = Math.round(delta / 1000 / 60 / 60/ 24); 

                return delta_in_days;
        }
4

3 に答える 3

1

正しい形式で日付を取得したら、それを他の日付と比較する必要もあります。Date()これを行うには、日付文字列をオブジェクトにキャストすることができます。

Dateまた、オブジェクトを作成するとすぐに、実際の形式は関係なくなることに注意してください。

まず、string.split('/') を使用して、日付をコンポーネントに分割する必要があります。

var date1 = new Date(year,month-1,day),
var date2 = new Date(year2,month2-1,day2);
delta = date2 - date1;
// delta is the difference in milliseconds
delta_in_days = Math.round(delta / 1000 / 60 / 60/ 24);
于 2012-09-19T16:17:30.120 に答える
0

このプラグインを使用して日付をフォーマットし、正確な日付比較のために ajax 経由でサーバーに渡します

そして、このように呼び出します

var start = $.format.date($('#startDate').val(), "dd/MM/yyyy");
var finish= $.format.date($('#finish').val(), "dd/MM/yyyy");

$.ajax({
        cache: true,
        type: 'post',
        async: false,
        data: { start: start, finish: finish },
        url: '/controller/CheckDates',
        success: function (msg) {

            //msg will be the days

        }
    });

経験からの不正確さのためにこのようにしました。より効率的な方法があるかもしれません

于 2012-09-19T16:08:28.350 に答える
-1

これは、日付形式をdd / mm/yyに設定する方法です。

$(function () {
    $(".datepicker").datepicker({ dateFormat: 'dd/mm/yy' });
});
于 2012-09-19T16:05:19.570 に答える