Reputation: 189
Hi I need to validate two date time moment instances, Using this Package to get time we can select hour min sec in this. I need validate if selected Date time is after or before like you see in code .I'm having confusion will it validate date with time ? How to compare selected date time hour min sec in isAfter/isBefore
function DateValidate(selectedDate,type){ //selected date in moment instance
let isValid=false
const {startTime,endTime}=dateTime // from state
if(type==='start'&& endTime){
isValid=selectedDate.isAfter(endTime);
}else if(type==='end'&& startTime){
isValid=selectedDate.isBefore(startTime);
}
return isValid
}
should i need to format selected date needed format -(dd/mm/yyyy hh:mm:ss) and then apply isBefore/isafter ? Please help...
Upvotes: 2
Views: 7905
Reputation: 41
It looks like, in your example, the selectedDate is not a valid moment object. selectedDate needs to be a valid moment object in order to successfully apply the isAfter() and isBefore() methods, and startTime and endTime must also be in the correct format. See the examples in the docs: https://momentjs.com/docs/#/query/is-after/.
If you know the format ahead of time, you can pass that as the second argument into moment(). See the relevant part of the docs: momentjs.com/docs/#/parsing/string-format. In your example, something like moment("10/09/1997 02:31:01", "dd/mm/yyyy hh:mm:ss")
Upvotes: 0
Reputation: 509
Yes it will validate date along with the time. Here is the code which shows the 1 second difference between two dates.
const out = document.getElementById('output');
const today = moment();
var afterToday;
setTimeout(()=>{
afterToday = moment();
}, 1000)
setTimeout(()=>{
//const diff = afterToday.isAfter(today);
const diff = today.isAfter(afterToday);
out.innerText = diff;
}, 2000)
To see it in action take a look here.
Upvotes: 2