How to set the Current month with its last date using JavaScript - javascript

For eg. Date is 2019-01-29 (Jan 29,2019)
I want set month January from 29 Date to 31 Date and display as 2019-01-31 as result using JavaScript

//Set this to whatever date you want..
var d = '2019-02-21';
//Parse out our date object a bit..
var asOf = new Date(d);
var year = asOf.getFullYear();
var month = asOf.getMonth();
//Initially set to first day of next month..
var desiredDate = new Date(year, month + 1, 1);
//Now just subtract 1 day to make it the last day of prior month..
desiredDate.setDate(desiredDate.getDate() - 1);
//Show the date of last day in month..
console.log(`The last day of ${month + 1}/${year} is: ${desiredDate.toLocaleString().split(',')[0]}`);

var date = new Date();
date.setMonth(date.getMonth() + 1);
date.setDate(-1);
Setting date to -1 sets it to the last day of the previous month.

Related

How to retrieve and set the last day of the month based on user input?

How to retrieve the last day of the month of user input in javascript?
I have a form with 2 datepickers. Currently, the form date is set as MM/YYYY (this is how I need it in the form) However, for date validation, I need the dates to be in format MM/DD/YYYY. The first date will just be set to MM/01/YYYY and the second date needs to be set as MM/lastDayOfMonth/YYYY.
Below is what I have done so far. Which returns the last day of the month but along with timestamp and day.
var monthYear2 = $("#date2").val();
var month = monthYear2.slice(0,2);
var year = monthYear2.slice(3,7);
var lastDay = new Date(year, month + 1, 0);
var date2 = monthYear2.slice(0, 3) + lastDay + "/" + monthYear2.slice(3, 7)
I need my final variable of date2 to be in the format of MM/lastDayOfMonth/YYYY
I don't get why you are creating a Date object with month + 1. Just use month if it is for the current month the user sent.
const userInput = '02/2019',
splitted = userInput.split('/'),
month = splitted[0],
year = splitted[1],
firstDayDate = `${month}/01/${year}`,
lastDayDate = `${month}/${new Date(year, month, 0).getDate()}/${year}`;
console.log(firstDayDate, lastDayDate);

Get week number of the month from date (weeks starting on Mondays)

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

How to get first and last day of current week when days are in different months?

For example, in the case of 03/27/2016 to 04/02/2016, the dates fall in different months.
var curr = new Date; // get current date
var first = curr.getDate() - curr.getDay();
var last = first + 6; // last day is the first day + 6
var firstday = new Date(curr.setDate(first)).toUTCString();
var lastday = new Date(curr.setDate(last)).toUTCString();
The getDay method returns the number of the day in the week, with Sunday as 0 and Saturday as 6. So if your week starts on Sunday, just subtract the current day number in days from the current date to get the start, and add 6 days get the end, e.g.
function getStartOfWeek(date) {
// Copy date if provided, or use current date if not
date = date? new Date(+date) : new Date();
date.setHours(0,0,0,0);
// Set date to previous Sunday
date.setDate(date.getDate() - date.getDay());
return date;
}
function getEndOfWeek(date) {
date = getStartOfWeek(date);
date.setDate(date.getDate() + 6);
return date;
}
document.write(getStartOfWeek());
document.write('<br>' + getEndOfWeek())
document.write('<br>' + getStartOfWeek(new Date(2016,2,27)))
document.write('<br>' + getEndOfWeek(new Date(2016,2,27)))
You can find below solution for your problem.
let currentDate = new Date; // get current date
let first = currentDate.getDate() - currentDate.getDay();
var last = first + 6; // last day is the first day + 6
let firstDayWeek = new Date(currentDate.setDate(first)).toISOString();
var lastDayWeek = new Date(currentDate.setDate(last)).toISOString();
console.log(firstDayWeek, "first Day in week")
console.log(lastDayWeek, "end Day in week")
I like the moment library for this kind of thing:
moment().startOf("week").toDate();
moment().endOf("week").toDate();
You can try this:
var currDate = new Date();
day = currDate.getDay();
first_day = new Date(currDate.getTime() - 60*60*24* day*1000);
last_day = new Date(currDate.getTime() + 60 * 60 *24 * 6 * 1000);

Month missing in getting dates for year if date is not available in month

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();
};

get 1st,last,today date

How do i get today's date, 1st day of current month and last day of current month?
see fiddle
var current = new Date(); // this one's pretty self explanatory
console.log('current: ' + current);
var last = new Date();
last.setMonth(last.getMonth() + 1); // go to next month
last.setDate(0); // setting date to 0 is last day of previous month
console.log('last: ' + last);
var first = new Date();
first.setDate(1); // setting date to 1 is first day of current month
console.log('first: ' + first);
Have a look at the Date object: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date

Categories