Moment.js - 日期比较:捕捉最小范围

时间:2015-03-25 00:51:37

标签: jquery validation date momentjs kendo-datepicker

我的表单有一个Kendo DatePicker和一个在执行form.submit()之前运行JavaScript函数的按钮。我需要能够将输入的日期与下限进行比较,并且如果它早于我的设定日期,则阻止代码继续(提交表单)。如果没有违反限制,我想返回false,如果有,则返回true。我将使用此示例来说明我在验证代码中要做的事情:

var lowerBound = new Date('1776', '6','4');  // July 4, 1776
var dateField = $('#myDateField').val();  // <-- comes from Kendo DatePicker
var dateToConsider = new Date(dateField);  // if this is 1/1/0001, this changes to 1/1/1901... not good, so I do this, instead....

var arrDate = dateField.split('/'); // I also check for '-', ' ', and '.'
dateToConsider = arrDate[2] + '-' + arrDate[0] + '-' arrDate[1]; // could add 'T00:00:00Z'; but don't think it matters

var momentDTC = moment(dateToConsider);
var lowerLimitBreached = moment(lowerBound).isAfter(momentDTC); // <-- this is always false

if (!lowerLimitBreached)
    $('form').submit();

我一直在向控件输入1/1/0001,并且它一直是lowerLimitBreached为假,当它应该为真时,因为1-1-0001明显早于7-4-1776 ...我尝试使用.isBefore(),但遇到了同样的问题,文档实际上是NOTE: moment().isBefore() has undefined behavior and should not be used!,所以我不敢使用它。

时刻文件:http://momentjs.com/docs/#/query/

2 个答案:

答案 0 :(得分:0)

由于您正在使用moment.js,因此根本不要使用JavaScript Date对象。坚持只使用时刻物体。

//evaluates correctly
moment('0001-01-01');

//evaluates to Feb 2, 0001 - makes no sense...
new Date(Date.parse('0001-02-03'))
                            //^ but that's a 3, not a 2

//true - Jan 1, 0001 is before June 4, 1776
moment('0001-01-01').diff(moment('1776-06-04')) < 0

所以,看看你的代码,试试看:

var lowerBound = moment('1776-06-04');
var dateField = $('#myDateField').val();

// String replace and put in proper format for moment
dateField = dateField.replace(/(\/)/g,'-');
var year = dateField.split('-')[2];
var month = dateField.split('-')[0];
var day = dateField.split('-')[1];

if (month < 10) { month = "0" + month; }
if (day < 10) { day = "0" + day; }
dateField = year + '-' + month + '-' + day;

// Enter into moment and compare
var dateToConsider = moment(dateField);
var lowerLimitBreached = dateToConsider.diff(lowerBound) < 0;

if (lowerLimitBreached)
    $('form').submit();

答案 1 :(得分:-1)

你为什么不这样做?

var lowerBound = moment('1776-6-4');
var dateField = moment($('#myDateField').val());
var lowerLimitBreached = moment(lowerBound).isAfter(dateField);

if (!lowerLimitBreached)
    $('form').submit();

您已经在使用片刻,只需将剑道选取器的日期转换为片刻对象,然后使用isAfterisBefore

如果这不起作用,请提供选择器可能返回但不适合您的日期