If I have a starting date of 31st of January and I add 1 month, it returns a date of 2nd of March.
I am trying to make a script that will add months to date in this way :
starting date : 31/01/2000
+1 month = 29/02/2000
+2 months = 31/03/2000
+3 months = 30/04/2000
....
+12 months = 28/02/2001
Another case :
Starting date : 28/02/2001
+1 month : 31/03/2001
+2 months : 30/04/2001
...
So, the idea is if starting date is the last day of the current month, ending date must be the last day of month.
So, my code logic is below :
var date = new Date(2017,01,30);
1. Get current day of this date. (x)
2. If x < days in this month, add 1 month to date
2.1 In same if, If modified date < x, set date to last day of previous month
3. Else of main if, set date to last day of next month
My JSFiddle is here : https://jsfiddle.net/5mfLo8zs/
Idk what is wrong in syntax, but it gives me a .getDate() is not a function error, probably, it's not the unique problem.
P.S. I know that this theme is duplicated, I took 10 minutes to search for identic question, but I found just how to set last day of month, but here I need something more.
You can try something like this:
Logic:
Check if date passed is the last day of the month?
If yes, you will need to add 1 to months. This is because, logic to get last day of month works by creating a date as 1st day of next month and then subtract 1.
Now initialize a temp variable that will hold value of day. Set it to 0 by default.
If months are same, set this temp variable to passed date's day. Else let it be 0.
Now you have all the parameters to create new date. Return it. Note, updating same date variable will override original value. So try to avoid any manipulations to it.
function addMonths(date, months) {
var d = 0;
var next = new Date(date.getFullYear(), date.getMonth(), date.getDate() + 1);
if (next.getMonth() === date.getMonth()) {
d = date.getDate()
}
else{
months++
}
// use following line in actual code.
// return new Date(date.getFullYear(), date.getMonth() + months, d)
// This line is just fror demonstration purpose.
return new Date(date.getFullYear(), date.getMonth() + months, d).toDateString();
}
console.log(addMonths(new Date(2017, 0, 31), 1));
console.log(addMonths(new Date(2017, 0, 31), 3));
console.log(addMonths(new Date(2017, 0, 15), 3));
console.log(addMonths(new Date(2016, 11, 31), 1));
console.log(addMonths(new Date(2016, 11, 11), 1));
Related
I have to find week number of the month from given date using JavaScript. Week start is Monday.
I have tried the code below but not getting accurate result.
function getWeekNumber(date) {
var monthStartDate = new Date(new Date().getFullYear(), new Date().getMonth(), 1);
monthStartDate = new Date(monthStartDate);
var day = monthStartDate.getDay();
date = new Date(date);
var date = date.getDate();
let weekNumber = Math.ceil((date + (day)) / 7);
return (weekNumber == 0) ? 1 : weekNumber;
}
var week = getWeekNumber('2020-04-04');
console.log(week);
Try this one
function getWeek(date) {
let monthStart = new Date(date);
monthStart.setDate(0);
let offset = (monthStart.getDay() + 1) % 7 - 1; // -1 is for a week starting on Monday
return Math.ceil((date.getDate() + offset) / 7);
}
getWeek(new Date(2019, 2, 14))
You could find the week number of the month for weeks starting on Monday (in line with the ISO week date system) by rolling the input date back to the previous Monday and then dividing the Monday date by 7 and rounding up to determine which week of the month the date falls in.
This approach will properly handle dates at the beginning of a month which actually fall in the last week of the previous month. For instance, 2020-04-04 is a Saturday in the week starting on 2020-03-30 (Monday), so it should return week 5 since it is part of the 5th week of March (and not part of the 1st week of April which starts on 2020-04-06, the first Monday in April).
For example (the split bit at the beginning is just to parse the date string rather than relying on new Date() to parse the string since that is not recommended due to browser inconsistencies):
const monthWeek = (s) => {
const [y, m, d] = s.split('-'); // parse date string
const date = new Date(y, m - 1, d); // create date object
date.setDate(d - ((date.getDay() + 6) % 7)); // adjust date to previous Monday
return Math.ceil(date.getDate() / 7); // return week number of the month
};
console.log(monthWeek('2020-04-04'));
// 5
console.log(monthWeek('2020-04-07'));
// 1
I have a dropdown on my page named Quarter which has following values -
Quarter 1
Quarter 2
Quarter 3
Quarter 4
Also i have another field named Year with Year values - 2015,2016,2-17,2-18,2019,2020
I want to define the values for each quarter in my javascript code like
if(quarter = "quarter 1")
{
startdate = 2017-01-01;enddate = 2017-01-31
}
And so on for other quarters as well.
I would like to ask if there is built-in functionality to get the startdate and enddate for each quarter and i will append the year field value to it.so that it does not remain static.
Any help would be appreciated.
Thanks in Advance
Quarter of a financial year starts on April 1 for many countries, so I would argue that you need to set the start of quarter 1 first.
Let's say
var startDate = new Date();
date.setMonth(2);
date.setDate(1);
Then you can have functions like
function addQuarter(date)
{
date.setMonth( date.getMonth() + 3 );
return date;
}
For example
addQuarter(date); //returns Thu Jun 01 2017
Similarly to get last date of quarter
function lastDateOfQuarter( date )
{
date.setMonth( date.getMonth() + 3 );
date.setDate( date.getDate() - 1);
return date;
}
You can format the date as per your requirements for display
function formatDate( date )
{
return date.getDate() + "-" + ( date.getMonth() + 1 ) + "-" + date.getFullYear();
}
I would like to ask if there is built-in functionality to get the startdate and enddate for each quarter and i will append the year field value to it.
Those are constants. Given your example for Q1, you're talking about the normal calendar quarters of a year. Q1 starts on 01/01 and ends on 31/03, Q2 starts on 01/04 and ends on 30/06, etc. Since no quarter starts or ends on the last day of February, this is not a moving target.
No, there's no built-in functionality, but you don't need any. Just construct dates from those constant month and day values and the year you need.
var q1 = {
start: new Date(2017, 0, 1), // Remember, January = 0 here
end: new Date(2017, 2, 31)
};
// ...
Or for UTC:
var q1 = {
start: new Date(Date.UTC(2017, 0, 1)),
end: new Date(Date.UTC(2017, 2, 31))
};
// ...
//if you are using current year
var todayDate=new Date();
var startMonth=todayDate.getMonth();
var startDay=1;
var endMonth=todayDate.getMonth();
var endtDay=31;
switch(quarterValue){
case "Q1" : startMonth=0;endMonth=2;
case "Q2" : startMonth=3;endMonth=5;
case "Q3" : startMonth=6;endMonth=8;
case "Q4" : startMonth=9;endMonth=11;
}
todayDate.setMonth(startMonth);
todayDate.setDate(startDay);
var startDate=todayDate;
todayDate.setMonth(endMonth);
todayDate.setDate(endDay);
var endDate=todayDate;
I am trying to get the dates for next year after provided date with following code
var dateArray = new Array();
dateArray.push(date);
for(var i=1;i<12;i++){
dateArray.push(new Date(date.getFullYear(),date.getMonth()+i,date.getDate()));
}
console.log(dateArray)
It is working fine if I select dates between 1-28 but when I select any date which is not available for any upcoming month it moves to next month.
what should happen here is I should be getting last date of month for which selected date is not available
The Date object type handles overflow of the day of the month by incrementing the month, just as you said. To do what you want, you need to add an if statement that checks if the date is correct, and fixes it if it isn't.
var date = new Date(2015, 2, 30);
var dateArray = new Array();
dateArray.push(date);
for (var i = 1; i < 12; i++) {
dateArray.push(new Date(date.getFullYear(), date.getMonth() + i, date.getDate()));
// check if the day of the month is correct.
// If it isn't, we know that it overflowed into the next month
if(dateArray[i].getDate() !== date.getDate()) {
// setting the day to 0 will set it to the last day of the previous month
dateArray[i].setDate(0);
}
}
console.log(dateArray)
if you want to gat last day of particular month and year
function daysInMonth (month,year) {
return new Date(year, month+1, 0).getDate();
};
I need a JavaScript function that returns the number of days remaining from a particular date of every year.
I found the following code, but how can I make it repeatable for every year, instead of changing the year in the function manually?
function daysUntil(year, month, day) {
var now = new Date(),
dateEnd = new Date(year, month - 1, day), // months are zero-based
days = (dateEnd - now) / 1000/60/60/24; // convert milliseconds to days
return Math.round(days);
}
daysUntil(2013, 10, 26);
I think my question above is not clear enough, i need to show days remaining in 26th October. So this starts again every year on 27th October. I don't need a loop for that.
"how can i make it repeatable for every year, instead of changing the year in function manually?"
Well you can't do literally every year to infinity, but you can easily add a loop to get a specific range of years:
var d;
for (var y = 2013; y < 2099; y++) {
d = daysUntil(y, 10, 26);
// do something with d, e.g.,
console.log(d);
}
UPDATE: You added this detail to your question:
"I think my question above is not clear enough, i need to show days remaining in 26th October. So this starts again every year on 27th October. I don't need a loop for that."
OK, that's still not very clear, but I think you're saying that your input would be just the day and month and you want to calculate the number of days until the next time that day/month rolls around, e.g., the number of days until your next birthday. If so, perhaps something like this:
function daysUntil(month, day) {
var now = new Date(),
currentYear = now.getFullYear(),
dateEnd = new Date(currentYear, month - 1, day); // months are zero-based
if (dateEnd - now < 0) // have we already passed that date this year?
dateEnd.setFullYear(currentYear + 1);
return Math.ceil((dateEnd - now) / 1000/60/60/24);
}
console.log(daysUntil(10,11)); // 365 - results from today, Oct 11
console.log(daysUntil(10,26)); // 15
console.log(daysUntil(7,7)); // 269
When I try to decrease a day from the date, the date has become zero instead of adjusting to the previous month date in java script. Below is the example.
var dt = new date(2012, 2, 1);
dt.setDate((dt.getDate() - 1));
logger.info(dt.getFullYear()+"-"+(dt.getMonth()+1) + "-" + dt.getDate());
Result is : 2012-2-0
It works fine, I think you're misunderstanding what the numbers are (although I never get 0). Although you did use new date(2012, 2, 1), but needs to be capitalized - new Date(2012, 2, 1).
When you use: new Date(2012, 2, 1), it creates the date "March 1st, 2012" since month (second parameter) is 0 based.
When you subtract a day, it will become "2012-2-29", which is "February 29th, 2012".
var dt = new Date(2012, 2, 1); // March 1st, 2012
dt.setDate((dt.getDate() - 1));
console.log(dt.getFullYear() + "-" + (dt.getMonth() + 1) + "-" + dt.getDate()); // February 29th, 2012
DEMO: http://jsfiddle.net/8PyFR/3/
You seemed to already understand that getMonth() returns a 0-based month, so you added 1. But just as you get a 1-based month (by adding 1), you must accommodate when setting a 1-based month (by subtracting 1). March is normally 3, but you need to use 2.