JavaScript: get all months between two dates? - javascript

I have two date strings like this:
var startDate = '2012-04-01';
var endDate = '2014-11-01';
And I want to end up with an array of strings like this:
var dates = ['2012-04-01', '2012-05-01', '2012-06-01' .... '2014-11-01',];
So far this is what I've got, but it's pretty ugly:
var startDate = '2012-04-01';
var endDate = '2014-11-01';
var start = new Date(Date.parse(startDate));
var end = new Date(Date.parse(endDate))
var dates = [];
for (var i = start.getFullYear(); i < end.getFullYear() + 1; i++) {
dates.push(i + '-' + '-01');
}
console.log(dates);
Is there a better way? JSFiddle.

This should produce the desired output:
function dateRange(startDate, endDate) {
var start = startDate.split('-');
var end = endDate.split('-');
var startYear = parseInt(start[0]);
var endYear = parseInt(end[0]);
var dates = [];
for(var i = startYear; i <= endYear; i++) {
var endMonth = i != endYear ? 11 : parseInt(end[1]) - 1;
var startMon = i === startYear ? parseInt(start[1])-1 : 0;
for(var j = startMon; j <= endMonth; j = j > 12 ? j % 12 || 11 : j+1) {
var month = j+1;
var displayMonth = month < 10 ? '0'+month : month;
dates.push([i, displayMonth, '01'].join('-'));
}
}
return dates;
}
Just call it with your existing date format:
dateRange('2013-11-01', '2014-06-01')
// ["2013-11-01", "2013-12-01", "2014-01-01", "2014-02-01", "2014-03-01", "2014-04-01", "2014-05-01", "2014-06-01", "2014-07-01", "2014-08-01", "2014-09-01", "2014-10-01", "2014-11-01", "2014-12-01"]

You can also use the excellent moment.js library:
var startDate = moment('2012-04-01');
var endDate = moment('2014-11-01');
var result = [];
if (endDate.isBefore(startDate)) {
throw "End date must be greated than start date."
}
while (startDate.isBefore(endDate)) {
result.push(startDate.format("YYYY-MM-01"));
startDate.add(1, 'month');
}
JSFiddle

If loading an extra library isn't a problem, you could always try the awesome MomentJS.
Gives for very clean and powerful date manipulation.
var startDate = moment('2012-04-01');
var endDate = moment('2014-11-01');
var dates = [];
endDate.subtract(1, "month"); //Substract one month to exclude endDate itself
var month = moment(startDate); //clone the startDate
while( month < endDate ) {
month.add(1, "month");
dates.push(month.format('YYYY-MM-DD'));
}
console.log(dates);
JSFiddle here

const getMonths = (fromDate, toDate) => {
const fromYear = fromDate.getFullYear();
const fromMonth = fromDate.getMonth();
const toYear = toDate.getFullYear();
const toMonth = toDate.getMonth();
const months = [];
for(let year = fromYear; year <= toYear; year++) {
let monthNum = year === fromYear ? fromMonth : 0;
const monthLimit = year === toYear ? toMonth : 11;
for(; monthNum <= monthLimit; monthNum++) {
let month = monthNum + 1;
months.push({ year, month });
}
}
return months;
}
const sample = getMonths(new Date('2022-07-28'), new Date('2023-03-20'));
console.log(sample);
document.write('check the console output');
https://jsfiddle.net/xfayoqvs/

You are handling "logical" jumps, so you doesn't actually need timing arthmetics. So this is a simple counting problem:
var startDate = '2012-04-01';
var endDate = '2014-11-01';
var dates = [];
var d0 = startDate.split('-');
var d1 = endDate.split('-');
for (
var y = d0[0];
y <= d1[0];
y++
) {
for (
var m = d0[1];
m <= 12;
m++
) {
dates.push(y+"-"+m+"-1");
if (y >= d1[0] && m >= d1[1]) break;
};
d0[1] = 1;
};
console.log(dates);

Here is a solution which just uses string manipulation on that specific YYYY-MM-DD format:
function monthsBetween(...args) {
let [a, b] = args.map(arg => arg.split("-").slice(0, 2)
.reduce((y, m) => m - 1 + y * 12));
return Array.from({length: b - a + 1}, _ => a++)
.map(m => ~~(m / 12) + "-" + ("0" + (m % 12 + 1)).slice(-2) + "-01");
}
console.log(monthsBetween('2012-04-01', '2014-11-01'));

Here is another solution, using Date objects:
const enumerateMonths = (from, to) => {
const current = new Date(from)
current.setUTCDate(1)
current.setUTCHours(0, 0, 0, 0)
const toDate = new Date(to)
const months = []
while (current.getTime() <= toDate.getTime()) {
months.push(current.getUTCFullYear() + "-" + `${current.getUTCMonth() + 1}`.padStart(2, "0"))
current.setUTCMonth(current.getUTCMonth() + 1)
}
return months
}
This solution presumes you provide Date objects or ISO 8601 strings. Please mind that an ISO 8601 date does not necessarily have to contain the hours-minutes-seconds part. "2012-01-14" is a valid ISO 8601 date.

An example to get all first days of months between a given date and now using moment.js.
var getMonths = function (startDate) {
var dates = [];
for (var year = startDate.year(); year <= moment().year(); year++) {
var endMonth = year != moment().year() ? 11 : moment().month();
var startMonth = year === startDate.year() ? startDate.month() : 0;
for (var currentMonth = startMonth; currentMonth <= endMonth; currentMonth = currentMonth > 12 ? currentMonth % 12 || 11 : currentMonth + 1) {
var month = currentMonth + 1;
var displayMonth = month < 10 ? '0' + month : month;
dates.push([year, displayMonth, '01'].join('-'));
}
}
return dates;
};

All solutions above run in O(n^2) time complexity, which is not very efficient.
See below solution in O(n) time complexity:
function getAllMonths(start, end){
let startDate = new Date(start);
let startYear = startDate.getFullYear();
let startMonth = startDate.getMonth()+1;
let endDate = new Date(end);
let endYear = endDate.getFullYear();
let endMonth = endDate.getMonth()+1;
let countMonth = 0;
let countYear = 0;
let finalResult = [];
for(let a=startYear; a<=endYear; a++){
if(startYear<endYear){
if(countYear==0){
countMonth += 12-startMonth;
}else
if(countYear>0){
countMonth += 12;
}
countYear+=1;
startYear++;
}else
if(startYear==endYear){
countMonth+=endMonth;
}
}
for(let i=startMonth; i<=countMonth+startMonth; i++){
finalResult.push(startDate.getFullYear()+(Math.floor(i/12)) + "-" + Math.round(i%13) + "-" + "01");
}
return finalResult;
}
getAllMonths('2016-04-01', '2018-01-01');
Might share a much more simpler code

Still not a very elegant answer, but arrives at the array of strings you want:
var startDate = '2012-04-01';
var endDate = '2014-11-01';
var start = new Date(startDate);
var end = new Date(endDate);
var dates = [];
for (var i = start.getFullYear(); i < end.getFullYear() + 1; i++) {
for (var j = 1; j <= 12; j++) {
if (i === end.getFullYear() && j === end.getMonth() + 3) {
break;
}
else if (i === 2012 && j < 4){
continue;
}
else if (j < 10) {
var dateString = [i, '-', '0' + j, '-','01'].join('');
dates.push(dateString)
}
else {
var dateString = [i, '-', j, '-','01'].join('');
dates.push(dateString);
}
}
}
console.log(dates);
jsfiddle link here: http://jsfiddle.net/8kut035a/

This is my solution, with help of math and O(n)
determineMonthInInterval(startDate, endDate) {
let startYear = startDate.getFullYear();
let endYear = endDate.getFullYear();
let startMonth = startDate.getMonth() + 1;
let endMonth = endDate.getMonth() + 1;
let monthAmount = (endMonth - startMonth) + 1 + (12 * (endYear - startYear));
let dates = [];
let currMonth = startMonth;
let currYear = startYear;
for( let i=0; i<monthAmount; i++){
let date = new Date(currYear + "/"+currMonth+"/1");
dates.push(date);
currYear = startYear + Math.floor((startMonth+i) / 12);
currMonth = (currMonth) % 12 +1;
}
return dates;
}

Here is another option:
getRangeOfMonths(startDate: Date, endDate: Date) {
const dates = new Array<string>();
const dateCounter = new Date(startDate);
// avoids edge case where last month is skipped
dateCounter.setDate(1);
while (dateCounter < endDate) {
dates.push(`${dateCounter.getFullYear()}-${dateCounter.getMonth() + 1}`);
dateCounter.setMonth(dateCounter.getMonth() + 1);
}
return dates;
}

Related

Javascript Parse Date Contract_End_Date

I have Contract_End_Date 2 version : 2020-1-1 and 2020-1-11
Result will be like: 2020-01-01 or 2020-01-11
What is solution here?
var updates = {};
var removes = {};
let Contract_End_Date = '2020-1-11';
if (typeof Contract_End_Date !== 'undefined' && Contract_End_Date != null) {
var arr = Contract_End_Date.split(" ");
if (arr.length == 2) {
var firstPart = arr[0];
var dateParts = firstPart.split("-");
if (dateParts.length == 3) {
var day = parseInt(dateParts[2]);
if (day < 10) {
day = "0" + day;
}
var month = parseInt(dateParts[1]);
if (month < 10) {
month = "0" + month;
}
var year = dateParts[0];
updates["Contract_End_Date"] = year + "-" + month + "-" + day;
}
}
}
console.log(updates);
For working with dates in JS, I can just recommend "Moment.js".
It makes your code much more simple and readable.
In your case:
let Contract_End_Date = '2020-1-11';
let formattedDate = moment(Contract_End_Date, 'YYYY-MM-DD').format('YYYY-MM-DD');
console.log(formattedDate);
// 2020-01-11
For more information: https://momentjs.com/
EDIT: Since Moment.js won't get updated with the newest features, it may be better to use other libaries like Luxon

How to get starting and ending days of each month in a date interval in js

i'm looking for a function which takes as parameters a starting and an ending date that returns an array of each first/ending days for each months in this interval.
Expected :
myFunction(new Date('2021-02-06'), new Date('2021-04-24'))
Expected output :
[
{begin: '2021-02-06', end: '2021-02-28' },
{begin: '2021-03-01', end: '2021-03-31' },
{begin: '2021-04-01', end: '2021-04-24' },
]
You can use next code:
myFunction(new Date('2021-02-06'), new Date('2021-04-24'));
function myFunction(startDateInput, endDateInput) {
var monthDifference = monthDiff(startDateInput, endDateInput)
var dates = [];
for (var i = 0; i <= monthDifference; i++) {
var month = startDateInput.getMonth();
var year = startDateInput.getFullYear();
// this gets first day in month
var startDate = new Date(year, month + i, 1)
// this gets last day in month
var endDate = new Date(year, month + i + 1, 0)
console.log('startDate', startDate);
console.log('endDate', endDate);
dates.push(
{
begin : startDate,
end : endDate
}
)
}
// this is to overwrite first and last date in array, it can be done better
dates[0].begin = startDateInput;
dates[monthDifference].end = endDateInput;
console.log('dates', dates)
}
function monthDiff(d1, d2) {
var months;
months = (d2.getFullYear() - d1.getFullYear()) * 12;
months -= d1.getMonth();
months += d2.getMonth();
return months <= 0 ? 0 : months;
}
Of course you can improve this code further. I made it quickly.
const formatDateString = (date) => {
const leadingZero = (d) => (100 + d + '').substr(1);
const y = date.getFullYear();
const m = leadingZero(date.getMonth() + 1);
const d = leadingZero(date.getDate());
return `${y}-${m}-${d}`;
};
const myFunction = (startIn, endIn) => {
const monthDifference = monthsDist(startIn, endIn);
const res = [];
const startYear = startIn.getFullYear();
const startMonth = startIn.getMonth();
const startDate = startIn.getDate();
for (let deltaM = 0; deltaM <= monthDifference; deltaM++) {
const monthStart = new Date(
startYear,
startMonth + deltaM,
deltaM ? 1 : startDate
);
const monthEnd =
deltaM < monthDifference ?
new Date(startYear, startMonth + deltaM + 1, 0) :
endIn;
res.push({
begin: formatDateString(monthStart),
end: formatDateString(monthEnd),
});
}
return res;
};
const monthsDist = (start, end) => {
const diffM =
(end.getFullYear() - start.getFullYear()) * 12 +
end.getMonth() -
start.getMonth();
return diffM > 0 ? diffM : 0;
};
console.log(myFunction(new Date('2021-02-06'), new Date('2021-04-24')));
console.log(myFunction(new Date('2020-02-06'), new Date('2021-04-24')));
console.log(myFunction(new Date('2021-04-06'), new Date('2021-04-24')));

How to check conditions for every day of a year in loop?

I got lot of selected data from fullcalendar. I need to get those selected date from one whole year. How to check that in for loop?
I tried few answers to add days one by one to my condition from some answers ,but its not working for me.
Here is my code I tried:
var t=$(#dttbl).datatable();
var arr = new Array();
var date = new Date(),
var Id = 1;
var d = date.getDate(),
month = date.getMonth(),
year = date.getFullYear()
var day1 = y + '-01-01';
var day365 = y + '-12-31';
for (i = day1; i < day365; day1.setdate(day1.getdate() + 1)) {
if (($(i.cell).css('backgroundColor', 'blue'))) {
arr.push(([Id,i,'test']));
Id++;
}
}
for (i = 0; i < arr.length; i++) {
t.row.add([
arr[i][0],
arr[i][1],
arr[i][2]
]).draw();
}
I tried this getdate(), day1.add(1).day(); , day1=moment(day1).add(1, 'days') to add one by one day to check my condition for full year? These are not working for me. Is there any other way to do it?
You can use the following as #mplungjan commented.
var arr = [];
var date = new Date('01-01-2019');
var DAY = 1000 * 60 * 60 * 24;
var day1 = date.getTime();
var day365 = day1+ 365*DAY;
var iDay = day1;
while(iDay < day365){
// pushing the value in arr for example.
arr.push(new Date(iDay));
// do your logic
iDay = iDay + DAY;
}
You can use daysInMonth function of moment.js to find how many days in each month. After that you can create your array.
var dates = [];
var year = new Date().getFullYear();
for (var i = 1, l = 12; i <= l; i++){
var daysInMonth = moment("2012-" + i, "YYYY-M").daysInMonth();
console.log("month : " + i)
console.log("days in month : " + daysInMonth)
for (i1 = 1, l1 = daysInMonth; i1 <= l1; i1++) {
dates.push(year + "-" + i + "-" + i1)
}
}
console.log(dates);

Need help finding what's wrong with my date range creation

I use Lodash and Momentjs to create a JSON date range with this structure :
{"days":[], "months": []}
Problem is :
At the moment dates are created but they are created more than necessary there is a lot of duplicates
Problem applies for months array and days array
Was like 2 days on this method but can't find why it doesn't work.
var startDate = moment();
var endDate = moment().add(61, 'days');
var months = [];
var range = {};
range.days = [];
range.months = [];
var currDate = startDate.clone().startOf('day');
var lastDate = endDate.clone().startOf('day');
while (currDate.add(1, 'days').diff(lastDate) < 0) {
var month = {};
month.name = currDate.clone().format('MMMM');
month.year = currDate.clone().format('YYYY');
var currentMonthDaysInTotal = moment(month.year + "-" + moment().month(currDate), "YYYY-MM").daysInMonth();
var daysIndex = 1;
while (daysIndex <= currentMonthDaysInTotal) {
var newDateForList = moment([month.year, moment().month(month.name).format('M'), daysIndex]);
if (newDateForList >= startDate && newDateForList <= endDate) {
range.days.push(newDateForList);
}
daysIndex++;
}
if (months.length === 0) {
months.push(month);
}
//regarder avec mitch
if (_.findIndex(range.months, function(o) {
return o.name !== month.name;
}) === -1) {
range.months.push(month);
}
}
console.log(range);
Here is a JSFiddle with my code for what I'm trying to do :
https://jsfiddle.net/Keldarne/LdLc6u0t/
Is this along the right lines of what you wanted?
var startDate = moment();
var endDate = moment().add(61, 'days');
var months = [];
var range = {};
range.days = [];
range.months = [];
var currDate = startDate.clone().startOf('day');
var lastDate = endDate.clone().startOf('day');
var monthYear = undefined;
while (currDate.add(1, 'days').diff(lastDate) < 0) {
range.days.push(currDate.clone());
var month = currDate.clone().format('MMMM'),
year = currDate.clone().format('YYYY');
if( month.concat( year ) !== monthYear ){
range.months.push({
name: month,
year: year
});
}
monthYear = month.concat( year );
}
console.log(range);

Get a list of dates between two dates using javascript

From JavaScript is there a way to get list of days between two dates from MySQL format. I don't want to use any library for this.
This is what i did.
function generateDateList(from, to) {
var getDate = function(date) { //Mysql Format
var m = date.getMonth(), d = date.getDate();
return date.getFullYear() + '-' + (m < 10 ? '0' + m : m) + '-' + (d < 10 ? '0' + d : d);
}
var fs = from.split('-'), startDate = new Date(fs[0], fs[1], fs[2]), result = [getDate(startDate)], start = startDate.getTime(), ts, end;
if ( typeof to == 'undefined') {
end = new Date().getTime();
} else {
ts = to.split('-');
end = new Date(ts[0], ts[1], ts[2]).getTime();
}
while (start < end) {
start += 86400000;
startDate.setTime(start);
result.push(getDate(startDate));
}
return result;
}
console.log(generateDateList('2014-2-27', '2014-3-2'));
I test it from chrome and nodejs below are the result.
[ '2014-02-27',
'2014-02-28',
'2014-02-29',
'2014-02-30',
'2014-02-31',
'2014-03-01',
'2014-03-02' ]
yeh big leap year:-D..., how can i fix this? or is there any better way.?
const listDate = [];
const startDate ='2017-02-01';
const endDate = '2017-02-10';
const dateMove = new Date(startDate);
let strDate = startDate;
while (strDate < endDate) {
strDate = dateMove.toISOString().slice(0, 10);
listDate.push(strDate);
dateMove.setDate(dateMove.getDate() + 1);
};
Take the start date and increment it by one day until you reach the end date.
Note: MySQL dates are standard format, no need to parse it by hand just pass it to the Date constructor: new Date('2008-06-13').
const addDays = (date, days = 1) => {
const result = new Date(date);
result.setDate(result.getDate() + days);
return result;
};
const dateRange = (start, end, range = []) => {
if (start > end) return range;
const next = addDays(start, 1);
return dateRange(next, end, [...range, start]);
};
const range = dateRange(new Date("2014-02-27"), new Date("2014-03-02"));
console.log(range);
console.log(range.map(date => date.toISOString().slice(0, 10)))
Here I use a recursive function, but you could achieve the same thing using a while (see other answers).
I have used this one from
https://flaviocopes.com/how-to-get-days-between-dates-javascript/
const getDatesBetweenDates = (startDate, endDate) => {
let dates = []
//to avoid modifying the original date
const theDate = new Date(startDate)
while (theDate < new Date(endDate)) {
dates = [...dates, new Date(theDate)]
theDate.setDate(theDate.getDate() + 1)
}
dates = [...dates, new Date(endDate)]
return dates
}
Invoke the function as follows:
getDatesBetweenDates("2021-12-28", "2021-03-01")
Note - I just had to fix issues with the Date object creation (new Date()) in the while loop and in the dates array. Other than that the code is pretty much same as seen on the above link
dateRange(startDate, endDate) {
var start = startDate.split('-');
var end = endDate.split('-');
var startYear = parseInt(start[0]);
var endYear = parseInt(end[0]);
var dates = [];
for(var i = startYear; i <= endYear; i++) {
var endMonth = i != endYear ? 11 : parseInt(end[1]) - 1;
var startMon = i === startYear ? parseInt(start[1])-1 : 0;
for(var j = startMon; j <= endMonth; j = j > 12 ? j % 12 || 11 : j+1) {
var month = j+1;
var displayMonth = month < 10 ? '0'+month : month;
dates.push([i, displayMonth, '01'].join('-'));
}
}
return dates;
}
var oDate1 = oEvent.getParameter("from"),
oDate2 = oEvent.getParameter("to");
var aDates = [];
var currentDate = oDate1;
while (currentDate <= oDate2) {
aDates.push(new Date(currentDate));
currentDate.setDate(currentDate.getDate() + 1);
}
I expanded Công Thắng's great answer to return {years, months, days}, thought it was worth sharing:
function getDates(startDate, endDate) {
const days = [],
months = new Set(),
years = new Set()
const dateMove = new Date(startDate)
let date = startDate
while (date < endDate){
date = dateMove.toISOString().slice(0,10)
months.add(date.slice(0, 7))
years.add(date.slice(0, 4))
days.push(date)
dateMove.setDate(dateMove.getDate()+1) // increment day
}
return {years: [...years], months: [...months], days} // return arrays
}
console.log(getDates('2016-02-28', '2016-03-01')) // leap year
/* =>
{
years: [ '2016' ],
months: [ '2016-02', '2016-03' ],
days: [ '2016-02-28', '2016-02-29', '2016-03-01' ]
}
*/
const {months} = getDates('2016-02-28', '2016-03-01') // get only months
Basically the function just increments the built-in Date object by one day from start to end, while the Sets capture unique months and years.

Categories

Resources