我正在使用angularjs和时刻库。我有一个对象start_date
,其中包含几个日期,一旦用户点击“继续”我将每个日期与今天进行比较,并在给定日期过去时抛出错误。
这是我的代码:
$scope.checkDateTime = function(){
angular.forEach($scope.orders.start_date,function(s){
console.log('data'+s);
if (moment(s).format('DD-MM-YYYY') < moment().format('DD-MM-YYYY')) {
swal({
title: "Please select a valid date.",
text: "Please select valid start date.",
confirmButtonClass: "btn btn-primary add-prod-btn",
imageUrl: 'images/vmy-sub.png'
})
return false;
}
}
}
编辑
当我安慰s
的价值时,我得到“27-10-2016”,当我使用moment(s, 'DD-MM-YYYY')
时,我得到“1477506600000”。因此,我认为我得到的价值不是字符串,但是当我直接将它与今天的日期比较时,它说的是“无效日期”,我很困惑。请帮忙。
如我在第一条评论中所述,您可以简单地使用isBefore
或isSameOrBefore
。
由于您的输入是一个字符串,您可以将parse转换为时刻对象,然后使用矩形方法。
你的病情是:
moment(s, 'DD-MM-YYYY').isBefore(moment())
您可以使用isAfter功能。
这项艰苦的工作对我有用
var sDate = new Date(document.addproject.sdate.value);
var eDate = new Date(document.addproject.edate.value);
var today = new Date();
var sy=sDate.getFullYear();
var sm=sDate.getMonth();
var sd=sDate.getDate();
var ey=eDate.getFullYear();
var em=eDate.getMonth();
var ed=eDate.getDate();
// var cymd=sDate - today;
var cy=today.getFullYear();
var cm=today.getMonth();
var cd=today.getDate();
var startdate=null;
var enddate=null;
// alert("some ");
if(sy < cy){
startdate="notgood";
}
else if(sm < cm){
startdate="notgood";
}
else if(sd < cd){
startdate="notgood";
}
else{
startdate="good";
}
if(ey < cy){
enddate="notgood";
}
else if(em < cm){
enddate="notgood";
}
else if(ed < cd){
endtdate="notgood";
}
else{
enddate="good";
}
if((document.addproject.sdate.value == "")||
(startdate !="good" ))
{
alert( "Please provide project Excepted Start Date !\n" +
"Start date must be valid " );
document.addproject.sdate.focus() ;
return false;
}
if((document.addproject.edate.value == "")||
(enddate !="good"))
{
alert( "Please provide project Excepted End Date!\n" +
"End date must be valid" );
document.addproject.edate.focus() ;
return false;
}
您也可以使用简单的Javascript日期方法来完成此操作。请检查下面。
$scope.checkDateTime=function(){
angular.forEach($scope.orders.start_date,function(s){
console.log('data'+s);
s = new Date(s);
var today = new Date();
if (s.getTime() < today.getTime()) { // Here "getTime()" converts the date to milliseconds where you can compare in terms of milliseconds. this worked well for me.
swal({
title: "Please select a valid date.",
text: "Please select valid start date.",
confirmButtonClass: "btn btn-primary add-prod-btn",
imageUrl: 'images/vmy-sub.png'
})
return false;
}
}
希望这可以帮助 :)