What I want here is if the user is exist and if the date is between the startdate and enddate the valid will return true;
var valid = false;
var { startDate, Related_To } = data // from form
var dd_startDate = ""
var assignes = ""
var dd_endDate = ""
// DATA_ENTRIES from database
DATA_ENTRIES.map((res=>{
assignes = res['assignedTo'];
dd_startDate = res['date'];
dd_endDate = res['end'];
}))
// I dont know why after loop no data is passed to empty variable. ex: dd_startDate = ""
var newStartDate = moment(dd_startDate).format('DD/MM/YYYY hh:mm A')
var newEndDate = moment(dd_endDate).format('DD/MM/YYYY hh:mm A')
valid = (Related_To == assignes && newStartDate > startDate && newEndDate < startDate)// I dont know if this will work
console.log("valid: ", valid)
return valid;
>Solution :
If you are using moment.js you can use the isBetween function
This uses the js date object so it works perfectly with hours and seconds
It works as the following :
moment('2010-10-20').isBetween('2010-10-19', '2010-10-25');
If you have format like 11/04/2022 11:28 AM you can use the moment constructor to create date Object like following :
moment("11/04/2022 11:28 AM", 'DD/MM/YYYY hh:mm A')
Here is an example
console.log('--------- TEST CLASSIC DATES ---------')
const startDate = new Date("2022-01-01")
const endDate = new Date("2022-12-31")
const testDate1 = new Date("2022-6-1")
console.log(moment(testDate1).isBetween(startDate, endDate)) //true
const testDate2 = new Date("2020-6-1")
console.log(moment(testDate2).isBetween(startDate, endDate)) //false
// testing with hours, minutes and secondes
const d1 = new Date(2022,3,11,10,0,0) // 11/04/2022, 10:00:00
const d2 = new Date(2022,3,11,12,0,0) // 11/04/2022, 12:00:00
console.log('--------- TEST DATES WITH HOURS ---------')
const checkDate = new Date(2022,3,11,11,0,0) // 11/04/2022, 11:00:00
console.log(moment(checkDate).isBetween(d1, d2)) //true
const checkDate2 = new Date(2022,3,11,14,0,0) // 11/04/2022, 14:00:00
console.log(moment(checkDate2).isBetween(d1, d2)) //false
// with your format
console.log('--------- TEST DATES WITH SPECIFIC FORMAT ---------')
const d3 = moment("14/04/2022 07:28 PM", 'DD/MM/YYYY hh:mm A')
console.log(moment(d3).isBetween(d1, d2)) //false
const d4 = moment("11/04/2022 11:28 AM", 'DD/MM/YYYY hh:mm A')
console.log(moment(d4).isBetween(d1, d2)) //true
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.2/moment.min.js"></script>