JavaScript - Get array of dates between start and end dates - javascript

I got this code (off GitHub) It does exactly what I want except the months produced are a month ahead of the months in the JavaScript code. The months in this code are 02 (February) but the months produced on screen are 03 (March). What am I not seeing here? Is it the way the dates are written?
<script>
// Returns an array of dates between the two dates
var getDates = function(startDate, endDate) {
var dates = [],
currentDate = startDate,
addDays = function(days) {
var date = new Date(this.valueOf());
date.setDate(date.getDate() + days);
return date;
};
while (currentDate <= endDate) {
dates.push(currentDate);
currentDate = addDays.call(currentDate,1);
}
return dates;
};
// Usage
var dates = getDates(new Date(2021,02,22), new Date(2021,02,27));
dates.forEach(function(date) {
document.write(date);
console.log(date);
});
</script>

As Timespider pointed out, getDates function is OK. You mus be careful when creating a new Date value, since months go from 0 to 11 in the Date constructor function:
// Usage
var fromFeb22 = new Date(2021,1,22);
var toFeb27 = new Date(2021,1,27);
var dates = getDates(fromFeb22 , toFeb27 );
dates.forEach(function(date) {
document.write(date);
console.log(date);
});
UPDATE: Using with jQuery's DatePicker
The jQuery's DatePicker widget has a getDate method which returns a Date object that you can use directly in your function (no need to use new Date()):
// Usage
var fromDate = $("#fromDate").datepicker("getDate");
var toDate = $("#toDate").datepicker("getDate");
var dates = getDates(fromDate, toDate);
dates.forEach(function(date) {
document.write(date);
console.log(date);
});
Using with standard date input <input type="date"/>
The standard date input returns the date as a string formatted like "yyyy-MM-dd", but it is easy to parse it into a Date object:
// Usage
var fromDate = new Date(document.querySelector("#fromDate").value);
var toDate = new Date(document.querySelector("#toDate").value);
var dates = getDates(fromDate, toDate);
dates.forEach(function(date) {
document.write(date);
console.log(date);
});

Related

How to return an array of all the dates between two selected dates using javascript

For my class assignment, I need to return an array of dates in between two selected dates on a calendar (arrival & departure).
I was given two sets of code that I can use, however I can't figure out how to link them together.
var arrival = document.getElementById('arrivalDate');
console.log(arrival.value);
var checkout = document.getElementById('departureDate');
console.log(checkout.value);
// Figure out the number of days they are check in for.
var days = checkout.value.split('-')[2] - arrival.value.split('-')[2];
console.log(days);
function dateRange(arrival, days) {
range = [];
// Starting At
return range;
}
// Returns an array of dates between the two dates
var getDates = function(startDate, endDate) {
var dates = [],
currentDate = startDate,
addDays = function(days) {
var date = new Date(this.valueOf());
date.setDate(date.getDate() + days);
return date;
};
while (currentDate <= endDate) {
dates.push(currentDate);
currentDate = addDays.call(currentDate, 1);
}
return dates;
};
// Usage
var dates = getDates(new Date(2013,10,22), new Date(2013,11,25));
dates.forEach(function(date) {
console.log(date);
});
Seems pretty simple when you've already been given the answer!
var arrivalDate = new Date(document.getElementById('arrivalDate').value);
var departureDate = new Date(document.getElementById('departureDate').value);
var dateRange = getDates(arrivalDate, departureDate);

Conditionally convert multiple formats of Date and DateTime string into JavaScript Date Object

With this little utility JavaScript function below it can convert a basic Date string into a JavaScript Date object.
The date string can be in multiple formats like this...
stringToDate("17/9/2014", "dd/MM/yyyy", "/");
stringToDate("9/17/2014", "mm/dd/yyyy", "/");
stringToDate("9-17-2014", "mm-dd-yyyy", "-");
What I am hoping to do is expand it to also allow conditionally strings that also have a Time in them 09:12:49 09:12:49am, 09:12:49pm
So my function below where it creates the Date object with this line...
var formatedDate = new Date(dateItems[yearIndex], month, dateItems[dayIndex]);
would have to instead do something like...
var formatedDate = new Date(dateItems[yearIndex], month, dateItems[dayIndex], hours, minutes, seconds, milliseconds);
adding the hours, minutes, seconds, milliseconds only if they are detected in the original string.
Would such a task be possibble with this code?
// Convert Date String into JS Date Object
// Can parse multiple Date formats
// stringToDate("17/9/2014", "dd/MM/yyyy", "/");
// stringToDate("9/17/2014", "mm/dd/yyyy", "/");
// stringToDate("9-17-2014", "mm-dd-yyyy", "-");
function stringToDate(d, _format, _delimiter) {
if((d instanceof Date)){
return d;
}
var formatLowerCase = _format.toLowerCase();
var formatItems = formatLowerCase.split(_delimiter);
var dateItems = d.split(_delimiter);
var monthIndex = formatItems.indexOf("mm");
var dayIndex = formatItems.indexOf("dd");
var yearIndex = formatItems.indexOf("yyyy");
var month = parseInt(dateItems[monthIndex]);
month -= 1;
var formatedDate = new Date(dateItems[yearIndex], month, dateItems[dayIndex]);
return formatedDate;
}
I am aware of MomentJS, DateJS, DateJS Evolved, and SugarJS but I am trying to do this for a small utility library.

compare string with today's date in JavaScript

I've got a string from an input field which I use for date with a format like this 25-02-2013. Now I want to compare the string with today's date. I want to know if the string is older or newer then today's date.
Any suggestions?
<script type="text/javascript">
var q = new Date();
var m = q.getMonth()+1;
var d = q.getDay();
var y = q.getFullYear();
var date = new Date(y,m,d);
mydate=new Date('2011-04-11');
console.log(date);
console.log(mydate)
if(date>mydate)
{
alert("greater");
}
else
{
alert("smaller")
}
</script>
Exact date comparsion and resolved bug from accepted answer
var q = new Date();
var m = q.getMonth();
var d = q.getDay();
var y = q.getFullYear();
var date = new Date(y,m,d);
mydate=new Date('2011-04-11');
console.log(date);
console.log(mydate)
if(date>mydate)
{
alert("greater");
}
else
{
alert("smaller")
}
You can use a simple comparison operator to see if a date is greater than another:
var today = new Date();
var jun3 = new Date("2016-06-03 0:00:00");
if(today > jun3){
// True if today is on or after June 3rd 2016
}else{
// Today is before June 3rd
}
The reason why I added 0:00:00 to the second variable is because without it, it'll compare to UTC (Greenwich) time, which may give you undesired results. If you set the time to 0, then it'll compare to the user's local midnight.
Using Javascript Date object will be easier for you. But as the Date object does not supports your format i think you have to parse your input string(eg: 25-02-2013) with '-' to get date month and year and then use Date object for comparison.
var x ='23-5-2010';
var a = x.split('-');
var date = new Date (a[2], a[1] - 1,a[0]);//using a[1]-1 since Date object has month from 0-11
var Today = new Date();
if (date > Today)
alert("great");
else
alert("less");
If your date input is in the format "25-02-2013", you can split the string into DD, MM and YYYY using the split() method:
var date_string="25-02-2013";
var day = parseInt(date_string.split("-")[0]);
var month= parseInt(date_string.split("-")[1]);
var year = parseInt(date_string.split("-")[2]);
The parseInt() function is used to make the string into an integer. The 3 variables can then be compared against properties of the Date() object.
The most significant points which needs to be remembered while doing date comparison
Both the dates should be in same format to get accurate result.
If you are using date time format and only wants to do date comparison then make sure you convert it in related format.
Here is the code which I used.
var dateNotifStr = oRecord.getData("dateNotif");
var today = new Date();
var todayDateFormatted = new Date(today.getFullYear(),today.getMonth(),today.getDate());
var dateNotif=new Date(dateNotifStr);
var dateNotifFormatted = new Date(dateNotif.getFullYear(),dateNotif.getMonth(),dateNotif.getDate());
Well, this can be optimized further but this should give you clear idea on what is required to make dates in uniform format.
Here's my solution, getDay() doesn't work like some people said because it grabs the day of the week and not the day of the month. So instead you should use getDate like I used below
var date = new Date();
var m = date.getMonth();
var d = date.getDate();
var y = date.getFullYear();
var todaysDate = formateDate(new Date(y,m,d));
console.log("Todays date is: " + todaysDate)
const formateDate = (assignmentDate) => {
const date = new Date(assignmentDate)
const formattedDate = date.toLocaleDateString("en-GB", {
day: "numeric",
month: "long",
year: "numeric"
})
return formattedDate
}
The function below is just to format the date into a legible format I could display to my users
<script type="text/javascript">
// If you set the timezone then your condition will work properly,
// otherwise there is a possibility of error,
// because timezone is a important part of date function
var todayDate = new Date().toLocaleString([], { timeZone: "Asia/Dhaka" }); //Today Date
var targetDate = new Date('2022-11-24').toLocaleString([], { timeZone: "Asia/Dhaka" });
console.log('todayDate ==', todayDate); // todayDate == 10/31/2022, 12:15:08 PM
console.log('targetDate ==', targetDate); // targetDate == 11/24/2022, 6:00:00 AM
if(targetDate >= todayDate)
{
console.log("Today's date is small");
}
else
{
console.log("Today's date is big")
}
</script>

Convert Returned String (YYYYMMDD) to Date

I have a string that contains 8 digits that represent a date. For example:
20120515
I'd like to compare it with today's date, created in this manner:
var currentDate = new Date();
How can I convert the "8 digit date string" to a suitable date format in order to compare it to currentDate?
Use the substring method and substring off 4 elements and assign it to your new date for the year. Then substring off two elements at a time and store the month and date accordingly.
var dateString = "20120515";
var year = dateString.substring(0,4);
var month = dateString.substring(4,6);
var day = dateString.substring(6,8);
var date = new Date(year, month-1, day);
var currentDate = new Date();
Now you can compare the two dates with the normal operators.
If you want a small date library you can use moment.js.
var a = moment("20120515", "YYYYMMDD");
// then use any of moment's manipulation or display functionality
a.format("MMM Do YYYY"); // May 15th 2012
a.fromNow(); // 14 hours ago
a.calendar(); // Today at 12:00 AM
To correctly handle the local time zone, it must explicitly summed to the calculated time
function dateStringToDate(dateString) {
try {
var year = dateString.substring(0, 4);
var month = dateString.substring(4, 6);
var day = dateString.substring(6, 8);
var date = new Date(year, month - 1, day);
const offset = date.getTimezoneOffset()
date = new Date(date.getTime() - (offset * 60 * 1000));
return date;
} catch (error) {
return null;
}
}
function dateStringToDate(dateString) {
try {
var year = dateString.substring(0, 4);
var month = dateString.substring(4, 6);
var day = dateString.substring(6, 8);
var date = new Date(year, month - 1, day);
const offset = date.getTimezoneOffset()
date = new Date(date.getTime() - (offset * 60 * 1000));
return date;
} catch (error) {
return null;
}
}
console.log(dateStringToDate("20211212"))
console.log(dateStringToDate("20211213"))
console.log(dateStringToDate("20211214"))
...some other "one-liner" ways to accomplish this:
(They take a value like dts='20020704'; and return date object [dt].)
var dt=new Date(dts.slice(0,4), (dts[4]+dts[5])-1, dts[6]+dts[7]);
...or...
var m=dts.match(/(....)(..)(..)/), dt=new Date(m[1],m[2]-1,m[3]);
...or...
var m=dts.match(/.{1,2}/g), dt=new Date(m[0]+m[1],m[2]-1,m[3]);
The last one's shortest, but the first is probably most efficient, since it doesn't use regex (but that's irrelevant, unless you're processing LOTS of data using this). I like the middle one best since it's easy to see what's happening.

Check the dates in JavaScript

I want to check two dates in java script. date format is YYYY-MM-dd.
var date1 = 2011-9-2;
var date1 = 2011-17-06;
Can anybody say how can I write condition?
If you mean that you want to compare them and your variables are strings, just use == for comparison.
var date1 = '1990-26-01';
var date2 = '2000-01-05';
if (date1 == date2) {
alert('date1 = date2')
}
else {
alert('something went wrong');
}
There are four ways of instantiating dates
var d = new Date();
var d = new Date(milliseconds);
var d = new Date(dateString);
var d = new Date(year, month, day, hours, minutes, seconds, milliseconds);
Here is the link to complete tutorial and function of creating, comparing dates http://www.w3schools.com/js/js_obj_date.asp
If you want to compare dates , have a look at the JS date object https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date , in particular the getTime() method .
Assuming the format is YYYY-MM-dd (your second date value breaks this rule) and that they are strings...
var date1 = '2011-9-2';
var date2 = '2011-06-17';
var fields = date1.split("-");
var d1 = new Date (fields[0], fields[1]-1, fields[2]);
var fields = date2.split("-");
var d2 = new Date (fields[0], fields[1]-1, fields[2]);

Categories

Resources