Is there any way in JavaScript that I can check if date is between 2 dates?
I have an array like
var unavailableDates = ["5-7-2011","6-7-2011","7-7-2011","15-7-2011","16-7-2011","17-7-2011" ];
and now I have 2 dates like 1-7-2011 and 10-7-2011. I want to see if any value from unavailableDates falls between these date. If it falls it should return alert.
Can someone help me on this? I am in process of learning more about JavaScript and jQuery. I am not able to code it the way I understood the problem.
Here you have the solution
var unavailableDates = ["5-7-2011","6-7-2011","7-7-2011","15-7-2011","16-7-2011","17-7-2011" ];
function str2date(sdate){ //This function gets a string and return a Date object
var parts = sdate.split("-");
return new Date(parts[2], parseInt(parts[1], 10)-1, parts[0]);
}
var stamp1 = str2date("1-7-2011").getTime(); //First date. getTime() converts it to an integer
var stamp2 = str2date("10-7-2011").getTime(); //Second date
for(var i=0; i<unavailableDates.length; i++){
var curStamp = str2date(unavailableDates[i]).getTime();
if(curStamp >= stamp1 && curStamp <= stamp2) //Check if it falls in range
alert(unavailableDates[i] + " falls in range");
}
Hope this helps. Cheers
Date object in JavaScript allows compare operation, you only required to have proper Date objects. Create Date objects from your bounds and array members and compare them in a loop.
More information about Date object could be found there: http://www.w3schools.com/js/js_obj_date.asp
Related
I am using a function in Angular JS to generate the dates for the past one week starting from today's date. I am storing these dates in an array and then using that array to flood a dropdown.
The following is the code that is being used by me.
generate() {
this.date_new = [];
var date = new Date();
var date1 = new Date();
for (var i = 0; i < 7; i++) {
date.setDate(date1.getDate() - i);
var a = date.toString();
var str = this.convert(a);
this.date_new.push(str);
}
}
Here convert is a function which is being used to convert the dates to the required format. A screenshot of generated dates is attached below.
As evident from the screenshot, the last two dates are incorrect. Can somebody explain to me, what the problem is?
The setDate() method sets the day of the Date object relative to the
beginning of the currently set month.
The above is from MDN.
Your code works for the first 5 dates, but once you are modifying your February date with -1, it sets the day relative to the current month e.g. February. So this will turn into January (as you are setting the day to -1), same happens in the next iteration and you get December.
For an easy fix you can just set the date variable to new Date() in the first line of your for loop.
The issue here is using the same date variable in the loop. You need to re-initialize it.
As can be seen in Parameters Value section in the link here. Zero and negative values in setDate() sets the date from previous month.
Hence at setDate(0), date value is set to last day of Feb. Now since you are using the same variable, setDate(-1) takes the previous month from Feb hence you get Jan.
You need to change the code to something like this:
generate() {
this.date_new = [];
var date1 = new Date();
for (var i = 0; i < 7; i++) {
// re-initialize date
var date = new Date();
date.setDate(date1.getDate() - i);
var a = date.toString();
var str = this.convert(a);
this.date_new.push(str);
}
}
Hope this helps :)
The issue here is that negative numbers inside the setDate method don't work quite well.
Please update the code to something like below:
this.date_new = [];
var date = new Date();
var date1 = new Date();
for (var i = 0; i < 7; i++) {
date= new Date(date1.getFullYear(), date1.getMonth(),date1.getDate()-i);
var a = date.toString();
var str = this.convert(a);
this.date_new.push(str);
}
Hope this will solve your problem.
I've tried using underscorejs, min and max methods but they can't handle strings. From what i've read and learnt anyway, since I get infinite back from both.
My array looks like : dateData = ["26/06/2016", "04/06/2016", "13/05/2016", "20/07/2016"]
How can I grab the last and the first date in these?
I tried using sort also that looks like : _.chain(dateData).sort().first().value() but I get back the last item in the array rather then the last date in the array.
var dateData = ["26/06/2016", "04/06/2016", "13/05/2016", "20/07/2016"];
function dateToNum(d) {
// Convert date "26/06/2016" to 20160626
d = d.split("/"); return Number(d[2]+d[1]+d[0]);
}
dateData.sort(function(a,b){
return dateToNum(a) - dateToNum(b);
});
console.log( dateData );
To retrieve the first, last date:
var firstDate = dateData[0];
var lastDate = dateData[dateData.length -1];
Basically, if you first convert all your 26/06/2016 to a date Number like 20160626 you can .sort() those numbers instead.
so you're basically sorting:
20140626
20140604
20140513
20140720
resulting in:
[
"13/05/2016",
"04/06/2016",
"26/06/2016",
"20/07/2016"
]
If we can format the dateStrings in a particular format, then sorting them as strings also sorts them as dates e.g. YYYY-MM-DD.
You can use localeCompare to compare strings.You can use following code to sort the dates:
dateData = ["26/06/2016", "04/06/2016", "13/05/2016", "20/07/2016"]
dateData.sort(function(a, b){
var A = a.split("/");
var B = b.split("/");
var strA = [ A[2], A[1], A[0] ].join("/");
var strB = [ B[2], B[1], B[0] ].join("/");
return strA.localeCompare( strB );
});
console.log( dateData );
Once sorted, you can get the min and max dates as:
var minDate = dateData[0];
var maxDate = dateData[ dateData.length - 1 ];
The getTime() method returns the numeric value corresponding to the
time for the specified date according to universal time. Date.getTime()
dateData = ["26/06/2016", "04/06/2016", "13/05/2016", "20/07/2016"]
.map(a=>a.split('/').reverse().join('/'))
.sort((a,b)=>new Date(a).getTime() - new Date(b).getTime());
console.log(dateData);
A number people have already touched on this, but you need to convert the date strings to something that can be compared in the sort function. The one thing I haven't seen shared is how to get the first and last dates. This should do the trick:
//original date array
var dateData = ["04/06/2016", "13/05/2016", "20/07/2016","26/06/2016"];
//map through the original array and convert the dates to js date objects
var formattedDates = dateData.map(function(date){
var splitDate = date.split("/")
return new Date(splitDate[2],splitDate[1]-1,splitDate[0])
})
//sort the dates
formattedDates.sort(function(a,b){
// Turn your strings into dates, and then subtract them
// to get a value that is either negative, positive, or zero.
return new Date(a) - new Date(b);
});
//Now you can get the first and last dates:
var firstDate = formattedDates[0]
var lastDate = formattedDates[formattedDates.length-1];
//log to check:
console.log('first date: ', firstDate)
console.log('last date: ', lastDate)
One way I know to do this is using the .sort() function for a string. https://msdn.microsoft.com/en-us/library/4b4fbfhk(v=vs.94).aspx
You would have to change your array into YYYY-MM-DD
then you could have the following code
var dateData = ["2016/06/26", "2016/06/04", "2016/05/13", "2016/07/20"];
dateData.sort();
var first = dateData[0];
var last = dateData[dateData.length-1];
where first is the earliest date and last is the latest date
To be easier for the subsequest operations, change the format to be like this: YYYY/MM/DD.
This way regular sorting will get you the min and max properly, and you won't need further parsing.
Helper function to sort would be like this:
for(var i=0;i<dateData.length;++i)
{
var split = dateData[i].split("/");
dateData[i] = split.reverse().join("/");
}
Roko's answer worked for me, and +1. And Jose had a similar thought to me, +1...
...There's an easier and more robust way: .valueOf()
converting date string to number:
const dateAsNumber = new Date(dateAsString).valueOf()
JS has a built in method/function for calculating the number of milliseconds that have passed since a date; that's .valueOf(), which can be called on a Date object. So, turn your date string into a Date object (with "new Date()" with the date string as the argument), and then convert to milliseconds.
After that, the normal .sort() works fine. As shown below, for your convenience:
const arrayOfDateStrings = ["5/01/2012", "10/01/2020", "10/01/2019", "11/30/2016", "10/01/2021", "02/01/2020"];
const sortedArray = arrayOfDateStrings.sort((a,b)=>new Date(a).valueOf() - new Date(b).valueOf());
console.log(sortedArray);
Or Moment.js can be used instead of the built-in Date object/functions, that works in a very similar way.
I have a very basic loop
console.log(thisStart);
console.log(thisEnd);
console.log(thisDate);
while(checkcounter < 10){
console.log(checkcounter);
thisDate = moment(thisDate,'MM/DD/YYYY').add(1,'days').toDate('MM/DD/YYYY');
console.log(thisDate);
checkcounter++;
}
I would expect that to give me the next day formated MM/DD/YYYY but instead the first iteration IS the next day but then it jumps 6 months.
Being a new moment.js user I am not sure where I am going wrong
The problem is in the statement inside the loop:
thisDate = moment(thisDate,'MM/DD/YYYY').add(1,'days').toDate('MM/DD/YYYY');
The first error is to pass a format string to the moment constructor when the first argument is a Date object. As described here, you need to pass a format string only if the first argument is a string containing a date:
thisDate = moment(thisDate).add(1,'days').toDate('MM/DD/YYYY');
The add invocation is correct but the doDate one is not. The function toDate does not take in input a format string:
thisDate = moment(thisDate).add(1,'days').toDate();
Here the complete snippet of code:
var thisDate = new Date(),
checkcounter = 0;
console.log('Init:', thisDate);
while (checkcounter < 10) {
console.log('Check counter:', checkcounter);
thisDate = moment(thisDate).add(1, 'days').toDate();
console.log('thisDate:', thisDate);
checkcounter++;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.6/moment.js"></script>
I'm having a form which is having two input fields with date picker(with the help of jquery ui).One asking a check in date & the other asking check out date.I want to calculate the Number of Days Between those two dates.I am a beginner to javascript.So can any one help me?
Use unix timestamp. It's universal tool when you working with time:
var a = new Date(2012,11,10);
var b = new Date(2012,11,12);
var dt = (b.getTime() - a.getTime())/(24*3600*1000) //2
You must first get the value of such input fields, eg:
var v1 = document.getElementById('input1Id').value;
var v2 = document.getElementById('input2Id').value;
then you have to instantiate two new Javascript Date objects:
var parts1 = v1.split('/');
var parts2 = v2.split('/');
// this will split your string into date parts, eg. 11/30/2012 would result as an array ['11','30','2012'];
var date1 = new Date(parts1[2],parts1[0],parts1[1]);
var date2 = new Date(parts2[2],parts2[0],parts2[1]);
// remember to check the index of array items considering your date format
finally, you just have to subtract one date from the other to get the difference in days:
var difference = Math.Abs(date1 - date2);
difference = parseInt(difference / 86400000);
//86400000 are the milliseconds in one day. Parsing to int will round the day - eg.5,4 days results as 5 day
Edit: Sure, you can reference your html element by his id attribute
<input type="text" id="myTextbox">
---
var txb = document.getElementById('myTextbox');
// do anything else to your txb here, if u like
txb.value = difference;
that's it!
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
JavaScript: formatting number with exactly two decimals
Can some one please help me with my java script?
My java script consistently counts up, the problem is the cents character length is way too long (need 2 characters max). Another problem is, I don't know what code additionally I need to put commas in the correct position for determining the proper amount. Example: 12345.67 vs 12,345.67. If some one can just take a look at the code, modify it and re-post the full code since I have no idea what to do, I would deeply appreciate it.
This is the javascript code: http://jsfiddle.net/pqsH6/
<p style="float:left;">Money Saved: </p><b><p id="ds" style="float:left;">$</p></b>
<div id="counter" style="float:left;"></div>
<script type="text/javascript">
var START_DATE = new Date("january 1, 2012 12:00:00"); // put in the starting date here
var INTERVAL = 1000; // savings per second
var INCREMENT = 0.005; // money saved per second
var START_VALUE = -50000; // configures proper savings calculation
var count = 0;
window.onload = function()
{
var msInterval = INTERVAL * 1;
var now = new Date();
count = parseInt((now - START_DATE)/msInterval) * INCREMENT + START_VALUE;
document.getElementById('counter').innerHTML = count;
setInterval("count += INCREMENT; document.getElementById('counter').innerHTML = count;", msInterval);
}
</script>
This looks like a way to format your output with commas using Javascript:
How to print a number with commas as thousands separators in JavaScript
function numberWithCommas(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
Just pass your numbers through the function as a parameter and it will return a comma delimited number.
Here's another function you can use to round out to two decimal places:
function formatCurrency(num) {
num = isNaN(num) || num === '' || num === null ? 0.00 : num;
return parseFloat(num).toFixed(2);
}
Then use the function like this
var roundedCurrencyAmt = numberWithCommas(formatCurrency(amtOfMoney));
Here's a working jsFiddle: http://jsfiddle.net/alexfromapex/Y2x8m/2/
Just a comment:
> var START_DATE = new Date("january 1, 2012 12:00:00");
Relies on the built–in Date function parsing the string correctly, but ECMA-262 specifies only one format (a version of ISO8601) that Date should parse and that isn't it. But not all browsers in use support that format.
Better to use something that is both specified and known to work everywhere, e.g.:
var START_DATE = new Date(2012,0,1,12);
which will create a new date of 2012-01-01 12:00:00 in the local timezone in all browsers, or if UTC is required then:
var START_DATE = new Date(Date.UTC(2012,0,1,12));