Check if date/time is BETWEEN two other date/times Javascript - javascript

var startDateTime = '15.04.2019 00:15';
var endDateTime = '17.05.2019 18:35';
var checkDateTime = '16.04.2019 13:15';
function(checkDateTime, startDateTime, endDateTime) {
// need codes to return true or false,.
// check "checkDateTime" is between "startDateTime" to "endDateTime"
}

Try this code:
var startDateTime = getDate('15.04.2019 00:15');
var endDateTime = getDate('17.05.2019 18:35');
var checkDateTime = getDate('16.04.2019 13:15');
function isBetween(checkDateTime, startDateTime, endDateTime) {
return (checkDateTime >= startDateTime && checkDateTime <= endDateTime);
}
function toDate(str){
var [ dd, MM, yyyy, hh, mm ] = str.split(/[. :]/g);
return new Date(`${MM}/${dd}/${yyyy} ${hh}:${mm}`);
}
console.log(isBetween(checkDate,startDate,endDate));
To compare it one time falls between a time interval on the same day use: -
var startTime = "00:35";
var endTime = "18:15";
var checkTime = "13:00";
function getMinutes(timeString){
let [hh, mm] = timeString.split(":");
return parseInt(hh)*60 + parseInt(mm);
}
function isTimeBetween(checkTime,startTime,endTime){
checkTime = getMinutes(checkTime);
return (checkTime >= getMinutes(startTime) && checkTime <= getMinutes(endTime));
}
console.log(isTimeBetween(checkTime,startTime,endTime));

You can use new Date().getTime() to get the number of milliseconds since the Unix Epoch. So that you can compared the date/time with the result from this function. You can do sth like that:
return new Date(startDateTime).getTime() <= new Date(checkDateTime).getTime() <= new Date(endDateTime).getTime();
Check this out:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getTime

I would suggest to check if your checkDateTime is greater than your startDateTime and less then endDateTime.
function checkDateTime(checkDateTime, startDateTime, endDateTime) {
return (new Date(startDateTime) >= new Date(checkDateTime))
&& (new Date(checkDateTime) <= new Date(endDateTime));
}

Here is yet another option which adds the method directly to the Date prototype:
var startDateTime = new Date('04/15/2019 00:15');
var endDateTime = new Date('05/17/2019 18:35');
var checkDateTime = new Date('04/16/2019 13:15');
var outOfRangeDate_EARLY = new Date('01/16/2019 13:15');
var outOfRangeDate_LATE = new Date('06/16/2019 13:15');
Date.prototype.inRange = function(startDate, endDate){
var this_ms = this.getTime();
return ( this_ms >= startDate.getTime() && this_ms <= endDate.getTime() )
}
/* Tests */
console.log('expected: true', 'actual:', checkDateTime.inRange(startDateTime, endDateTime))
console.log('expected: false', 'actual:', outOfRangeDate_EARLY.inRange(startDateTime, endDateTime))
console.log('expected: false', 'actual:', outOfRangeDate_LATE.inRange(startDateTime, endDateTime))
This way, with any date you have var someDate, you can just call someDate.inRange(startDate, endDate). Sometimes, however, messing with the native prototypes can come back to haunt you if not careful. If so, having a separate function as answered by the others is very good.
Lastly, it's very important that the date strings are formatted properly before creating the Date objects, otherwise you'll encounter Invalid Date a lot. I hope this helps.

Related

how to compare the current date with the input date in java script or jquery

I'm using cleandersonlobo:date-picker-materialize package to input the date and I want to display an alert("expired") if the input date is less than the current date.
var $strDate = $(".pmt-date").val();
var $dtDate = $.datepicker.parseDate("mm/dd/yy", $strDate);
var $strToday = $.datepicker.formatDate('mm/dd/yy', new Date());
var $tDate = $.datepicker.parseDate('mm/dd/yy', $strToday);
if ($dtDate < new Date()) {
$('#myModal1').modal('hide');
alert("Job expired");
}
Try following code,
var $strDate = $(".pmt-date").val();
var $dtDate = $.datepicker.parseDate("mm/dd/yy", $strDate);
var $strToday = $.datepicker.formatDate('mm/dd/yy', new Date());
var $tDate = $.datepicker.parseDate('mm/dd/yy', $strToday);
if ($dtDate < $strToday ) {
$('#myModal1').modal('hide');
alert("Job expired");
}
A toMidnight function that sets the time of a date to midnight and by doing so removes time as a factor for your comparison:
function toMidnight(date) {
var midnight = arguments.length > 0 ? new Date(date) : new Date();
midnight.setHours(0);
midnight.setMinutes(0);
midnight.setSeconds(0);
midnight.setMilliseconds(0);
return midnight;
}
Then you can compare your date like this:
toMidnight($dtDate) < toMidnight()

Display one day with d3.slider

I have my map where I display some incidents over time. Until now I used the data which is filtered like this
dpG = d3.time.format("%d.%m.%Y").parse;
dpS = d3.time.format("%Y-%m-%d").parse;
var minDate = dpG("01.01.2015");
var maxDate = dpG("31.12.2015");
var secondsInDay = 60 * 60 * 24;
d3.select('#slider3').call(d3.slider()
.axis(true).min(minDate).max(maxDate)
.on("slide", function(evt, value) {
newDataG = site_dataG.features.filter(function(d){
var date = (dpG(d.properties.date).getTime() === new Date(value).getTime());
// console.log(date)
//console.log(new Date(value));
console.log(dpG(d.properties.date));
return(date);
});
// newDataS = site_dataS.features.filter(function(d){
// return dpS(d.properties.Date) < new Date(value);
// });
// console.log(newDataG);
// console.log("New set size ", newDataG.length);
displaySitesG(newDataG);
// displaySitesS(newDataS);
})
);
But now I tried to filter for only one day and not for all days until new Date(value)
So I tried something like this
newDataG = site_dataG.features.filter(function(d){
var date = dpG(d.properties.date) == new Date(value);
// console.log(date)
//console.log(new Date(value));
return(date);
});
Which turned out to be not working at all.
And something like this displays all data at once.
var date = new Date(value);
The other files is github repo if you need to see
EDIT2:
date1 = Math.round(dpG(d.properties.date).getTime() / (1000*60*60*24));
date2 = Math.round(new Date(value).getTime() / (1000*60*60*24));
console.log(date1);
console.log(date2)
gives me this
Checking for equality directly doesn't work with date objects:
var d1 = new Date();
var d2 = new Date(d1);
console.log(d1 == d2); // false!
Instead, you need to use th date.getTime() operator if you want to use the ==, !=, ===, and !== operators:
var d1 = new Date();
var d2 = new Date(d1);
d1.getTime() === d2.getTime(); // true
So, try this instead: (edited to fix error)
var date = (dpG(d.properties.date).getTime() === new Date(value).getTime());
Note that this will only work if dpG(thing) returns a Date object.
I used moment.js to make the UnixTimeStamp even
here is the code snippet which helped
d3.select('#slider3').call(d3.slider()
.axis(true).min(minDate).max(maxDate)
.on("slide", function(evt, value) {
sliderDate = moment(value,"x").utc().format("YYYY-MM-DD");
newDataS = site_dataS.features.filter(function(d){
//sliderDate = moment(value,"x").utc().format("YYYY-MM-DD");
dataDate = d.properties.Date;
//dataDateStampS = moment(dataDate).unix();
if (dataDate == sliderDate) {
return dpS(dataDate);
}
});
displaySitesS(newDataS);
})
);

Java script time compare with given time

Ok I cant get my head round this, ive looked at so many posts on SF but cant figure it out.
I need to campare server time with hardcorded time.
i have try this
var breackfastCutOffTime = "5:30";
var lunchCutOffTime = "10:00";
var dinnerCutOffTime = "17:00";
var serverTime = currentDate.getHours()+ ":" + currentDate.getMinutes();
if(Date.parse(toDay) == Date.parse(selectedDate)){
if(serverTime >= breackfastCutOffTime ){
document.getElementById("breakfast").disabled = true;
}else if(serverTime >= lunchCutOffTime){
document.getElementById("lunch").disabled = true;
}else if(serverTime >= dinnerCutOffTime){
document.getElementById("dinner").disabled = true;
}
}
I know this cant compare because time are in text format.Some one pleace help me to compleate this.
You can write a function which converts Time(hh:mm) in minutes(mm) only. Then you can compare two times and do your operations accordingly.
pseudocode:
function convert(string time) int {
//split the time by ':'
//convert the string hh,mm to int hour,mm
//calculate total minutes
//return total minutes
}
Refer Date Api for more info.
Below is your modified code. I have commented few lines. Modify according to your logic
Fiddler link
//var breackfastCutOffTime = "5:30";
var breackfastCutOffTime = new Date();
breackfastCutOffTime.setHours(5);
breackfastCutOffTime.setMinutes(30);
//var lunchCutOffTime = "10:00";
var lunchCutOffTime = new Date();
lunchCutOffTime.setHours(10);
lunchCutOffTime.setMinutes(00);
//var dinnerCutOffTime = "17:00";
var dinnerCutOffTime = new Date();
dinnerCutOffTime.setHours(17);
dinnerCutOffTime.setMinutes(00)
var serverTime = new Date();
//var serverTime = currentDate.getHours()+ ":" + currentDate.getMinutes();
//if(Date.parse(toDay) == Date.parse(selectedDate)){
if(serverTime >= breackfastCutOffTime ){
console.log("breackfastCutOffTime");
//document.getElementById("breakfast").disabled = true;
}else if(serverTime >= lunchCutOffTime){
//document.getElementById("lunch").disabled = true;
console.log("lunchCutOffTime");
}else if(serverTime >= dinnerCutOffTime){
//document.getElementById("dinner").disabled = true;
console.log("dinnerCutOffTime");
}
//}
Explanation:
Instead of converting the Date format to string i am creating new instance of the date for each cutoff time and setting desired time to that object.
Finally compare the date objects directly.
Note: The Date objects are set according to your timezone.
You can pass the breackfastCutOffTime,lunchCutOffTime and dinnerCutOffTime to the below function and it will return true if they are equal to or greater than current time.
function compareTime(timeToCompare) {
var currentDate = new Date();
var tempDate = new Date();
var timeToCompareArray = timeToCompare.split(":");
tempDate.setHours(timeToCompareArray[0]);
tempDate.setMinutes(timeToCompareArray[1]);
if (tempDate >= currentDate) {
return true;
} else {
return false;
}
}

Get Month as well as date in my variable - javascript

Hi i am trying to do a IF statement which allows the current date to be compared to the input date.. if the input date is below the current date it will be false.
I have got the date passing through my variable but it only stores the number so for example it compares day 9 to another day, which is not very reliable. I want the variable to take in the month and the year as well, meaning it can compare the ENTIRE DATE.
If there is a better way let me know.
Here is my code
if (this.element.find('#visitdate').length > 0) {
var dateParts = $('#visitdate').val().split('/');
var check = new Date(dateParts[2], dateParts[1], dateParts[0], 0,0,0,0).getDate();
var today = new Date().getDate;
if (check < today) {
_errMsg = "Please enter a furture visit date";
return false;
} else {
return true;
}
}
Your line for today's date contains an error:
var today = new Date().getDate;
should be
var today = new Date().getDate();
format as mm/dd/yyyy
var from = '08/19/2013 00:00'
var to = '08/12/2013 00:00 '
var today = new Date().getDate();
function isFromBiggerThanTo(dtmfrom, dtmto){
var from = new Date(dtmfrom).getTime();
var to = new Date(dtmto).getTime() ;
return from >= to ;
}
or using below
var x = new Date('2013-05-23');
var y = new Date('2013-05-23');
and compare
You can try this - it's working fine in my project -
Step 1
First Create javascript function as below.
Date.prototype.DaysBetween = function () {
var intMilDay = 24 * 60 * 60 * 1000;
var intMilDif = arguments[0] - this;
var intDays = Math.floor(intMilDif / intMilDay);
if (intDays.toLocaleString() == "NaN") {
return 0;
}
else {
return intDays + 1;
}
}
Step 2
-
var check = new Date(dateParts[2], dateParts[1], dateParts[0], 0,0,0,0).getDate();
var today = new Date().getDate;
var dateDiff = check .DaysBetween(today);
// it will return integer value (difference between two dates )
if(dateDiff > 0 ){ alert('Your message.......');}
You can have this much easier.
You dont need to check with getDate() property you can just compare 2 dates.
And also is not needed to initialize with hours, minutes and seconds the Date, you only need year, month and date.
Here you have your example simplified
var dateParts = $('#visitdate').val().split('/');
var check = new Date(dateParts[2], dateParts[1], dateParts[0]);
var today = new Date();
if (check < today) {
return false;
} else {
return true;
}
http://jsfiddle.net/wns3LkLv/
Try this:
var user="09/09/2014/5/30";
var arrdt= user.split("/");
var userdt = new Date(arrdt[2], arrdt[1] - 1, arrdt[0],arrdt[3],arrdt[4]);
var currdt = new Date();
if (userdt < currdt) {
alert("userdate is before current date"); //do something
}else{
alert("userdate is after current date"); //do something
}
Thanks for all your answers guys i have fixed it.
I used the getTime function instead of getDate.
Then the check variable had to have a -1 assigned to the month as it was going 1 month to high.
var check = new Date(dateParts[2], dateParts[1]-1, dateParts[0], 0,0,0,0).getTime();
Cheers

Change Date so all hours are offset by 4 hour

I want to adjust the Date object to always be 4 hours offset. How would I achieve this?
var d = new Date();
// d would be 4 hours in the past
Something like this:
d.setHours(d.getHours()-4);
Date.withOffset = function( offset ){
var r = new Date();
r.setHours(r.getHours()+offset);
return r;
};
var d = Date.withOffset( -4 )
// d would be 4 hours in the past
You may come up with a better name.
If you wish to break all javascript on your page you may of course use:
Date = function () {
var old = Date;
function broken() {
var r = new old();
r.setHours(r.getHours()-4);
return r;
}
broken.fix = function () {
Date = old;
};
return broken;
}();
You can then fix it by calling Date.fix()
You can create a date object with a particular date. Just subtract the correct milliseconds from the current time and pass that to the date function:
var d = new Date(new Date().getTime() - 1000*60*60*4);
or you can manually set the hours
var d = new Date();
d.setHours((12 + (d.getHours() - 4))%12)

Categories