MomentJS - How to get last day of previous month from date? - javascript

I'm trying to get last day of the previous month using:
var dateFrom = moment(dateFrom).subtract(1, 'months').format('YYYY-MM-DD');
Where:
dateFrom = 2014-11-30
But after using
subtract(1, 'months')
it returns date
DATE_FROM: "2014-10-30"
But last day of the 10'th month is 31.
How can I solve i please?
Many thanks for any help.

Simply add a endOf('month') to your calls:
var dateFrom = moment(dateFrom).subtract(1,'months').endOf('month').format('YYYY-MM-DD');
http://jsfiddle.net/r42jg/327/

An even easier solution would be to use moment.date(0). the .date() function takes the 1 to n day of the current month, however, passing a zero or negative number will yield a dates in the previous month.
For example if current date is February 3rd:
var _date = moment(); // 2018-02-03 (current day)
var _date2 = moment().date(0) // 2018-01-31 (start of current month minus 1 day)
var _date3 = moment().date(4) // 2018-02-04 (4th day of current month)
var _date4 = moment().date(-4) // 2018-01-27 (start of current month minus 5 days)
console.log(_date.format("YYYY-MM-DD"));
console.log(_date2.format("YYYY-MM-DD"));
console.log(_date3.format("YYYY-MM-DD"));
console.log(_date4.format("YYYY-MM-DD"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.20.1/moment.js"></script>

Last month's First date and last month's last date from the current date basis. The Format of the date changes depending upon. (DD-MM-YYYY)
console.log("last month first date");
const lastmonthlastdate=moment().subtract(1, 'months').startOf('month').format('DD-MM-YYYY')
console.log(lastmonthlastdate);
console.log("lastmonth last date");
const lastmonthfirstdate=moment().subtract(1, 'months').endOf('month').format('DD-MM-YYYY')
console.log(lastmonthfirstdate);

moment().subtract(1, 'months').endOf('month').format('YYYY-MM-DD')

You can get the first day of the month then subtract 1 day to get the last day of the previous month.
const monthyear = moment().format('YYYY-MM')
const firstDay = moment(monthyear + "-01").format("YYYY-MM-DD");
// Subtract 1 day to get the end of the previous month
const dateTo = moment(firstDay).subtract('1', 'days').format("YYYY-MM-DD");

Related

Recurring date using dayjs with dayrs-recur

I’m willing to create a recurring date based on "nth weekday of month"
Here is my solution work when I select current Date
let dates = {};
const currentDate = dayjs();
const recurrence = currentDate
.recur(dayjs().add(4, "month"))
.every("Wednesday")
.daysOfWeek()
.every(currentDate.monthWeekByDay())
.weeksOfMonthByDay();
recurrence.all().forEach((date) => {
dates[date.format("YYYY-MM-DD")] = { selected: true, };
});
// dates = ["2022-09-21","2022-10-19","2022-11-16","2022-12-21","2023-01-18"]
but if put last day of this month which is 30
let dates = {};
const lastDayofMonth = dayjs().endOf("month");
const recurrence = lastDayofMonth
.recur(dayjs().add(4, "month"))
.every("Friday")
.daysOfWeek()
.every(lastDayofMonth.monthWeekByDay())
.weeksOfMonthByDay();
I was expecting to get
["2022-09-30","2022-10-28","2022-11-25","2022-12-30"..]
instead of
["2022-09-30","2022-12-30"]
Here is demo
Am I missing something ?
Thanks in advance
It possible to create a recurring date based on "nth weekday of month" with dayjs and dayjs-recur as all months as different number of weeks
But there are some challenges:
A month has 4 weeks on average (some months have few or no days for fifth week)
Due to this there may be cases where there is no fifth week or the fifth week doesn't have the nth weekday
To resolve this
If you are getting an nth weekday of month where the week is the last week of the month (could be 4th/5th week)
Get both the nth weekday of month for the last week (5th) and the fourth (4th) week
From the list of dates returned filter if dates for a month occur multiple times and select the latest/greatest one
The filtered result should have the nth weekday of month where the week is the last week of the month
Demo
Below is a link to a working demo forked from #Achraf's demo on code sandbox
Demo Link
Code Example
const lastDayofMonth = dayjs().endOf("month");
const recurrence = lastDayofMonth
.recur(dayjs().add(4, "month"))
.every("Friday")
.daysOfWeek()
.every([3, 4])
.weeksOfMonthByDay();
// filter recurrence
const months = {};
recurrence.all().forEach((date) => {
months[date.month()] = date;
})
// get filtered dates
const filteredDates = Object.values(months);
// formot date into dates object
filteredDates.forEach((date) => {
dates[date.format("YYYY-MM-DD")] = { selected: true, color: "#2FB0ED" };
});
console.log("dates", dates);
// ["2022-09-30","2022-10-28","2022-11-25","2022-12-30"..]

How to find if today day of the month is greater then a particular date on the month with date-fns

How can I find if todays date of the month is greater then 10 with date-fns
Basically I can get the first day of the month with startOfMonth
then add 10 days to that with addDays and then use ifAfter of isBefore.
The code could be looking like that:
greaterThan = 10;
today = new Date();
targetDate = addDays(startOfMonth(today), greaterThan);
isGreater = isAfter(today, targetDate);
Is there a shortcut withing date-fns to achieve in less code lines?
var greaterThan10 = new Date().getDate() > 10;
Cause the (numerical) day of today will be greater (or not) in any other month as well? Or am I missing something?

How to use moment to find first monday 18 month ago

I am writing some javascript and came across moment library.I would like to use the moment to get the first Monday of 18 Month ago. How would I do it?
I know 18 months ago it is
moment().subtract(18, 'months');
But how would I know the first Monday of that time.
Thanks ahead of time!
You can do this in one line.
moment().subtract(18,'months').startOf('month').add(6 - moment().day("Monday").day() ,'days').startOf('week').day(1);
Find the moment 18 months ago, get the start date of that month, add 6 days since in worst case the first of that month is a tuesday(results in a date which is in the week that includes the first monday) and then get the start of that week.
Voila, all in one line.
1st edit: corrected the calculation to be locale independent and always return a Monday and not beginning of week since that is locale dependent.
2nd edit: locales makes it a bit more complicated. Adding 6 days to a Monday with a locale where the week ends on Saturday will move into another week thus we need to adapt the algorithm to take the Monday week number into consideration, i.e. subtract moment().day("Monday").day() which gives the locale dependent week day number of a Monday(0 or 1). Changed in the code above.
cleaner and more reusable IMHO ;)
var monday = moment().day('Monday').weekday();
var searchFirstMonday = moment().subtract(18, 'months').startOf('month');
while (searchFirstMonday.weekday() !== monday){
searchFirstMonday.add(1, 'day');
}
If you go back 18 months, get the first day of that month, then the Monday of that week, you'll get close:
moment().subtract(18, 'months').startOf('month').day(1)
To make sure the Monday is in the right month, you need to break that down a bit:
var month = moment().subtract(18, 'months');
var firstMonday = month.startOf('month').day(1);
if (firstMonday.month() != month.month()) {
firstMonday = firstMonday.add(7, 'days');
}
If anyone wants to do the same without any libraries.
Not sure if this is the best way to do it :P
var now = new Date();
//Get year and month
var month = now.getMonth();
var year = now.getFullYear();
//Months to go back
var monthsIntoPast = 18;
//Day of week we're looking for
var firstWeekDay= 2;
//Loop for one week
for(var x = 0; x < 7; x++) {
//Go back 18 months to first day + x of the month
var past = new Date(year, month - monthsIntoPast, 2 + x);
//First monday
if(past.getDay() == firstWeekDay) {
//First monday 18 months ago
alert(past.toUTCString())
break;
}
}
You use the following code to get what you need:
// Subtract 18 months from the current date, then get the first day of the month
var date = moment().subtract(18, 'months').startOf('month');
// Get current month
var month = date.month();
// Get monday of the first week of the month
var firstMonday = moment(date).weekday(0);
// Check if the first day of the month is not Monday
// and first monday of first week is in the desired month
if( date.weekday() != 0 && firstMonday.month() != month ){
// Add 1 week if needed
firstMonday.add(1, 'weeks');
}
The example above consideres Monday as the first day of the week. If Monday is not the first day of the week (day with index 0), you can get the correct index using moment.weekdays()
var moment = require('moment');
date = moment().subtract(18, 'months').startOf('month');
First we get the the current date and subtract 18 months. Then we find the start of the month, which as of today is
_d: Tue Jul 01 2014 00:00:00 GMT-0800 (AKDT),
So now we need to adjust for the next Monday. We get the current day of the week with date.day() which will give us a number between 0-7 with 0 being last Sunday and 7 being next Sunday. In this case, the first is on a Tuesday.
>date.day();
2
So we take the offset of the day of the week and subtract it from 8. Why 8 you say? Because if you count every number including 0 and 7 there are 8 numbers. (Think arrays)
//since it's not monday we add the offset
date = date.add(8-date.day(), 'days');
In your code you'd want to check if the First day returned actually IS a Monday so as to not get the second Monday of the month. So the whole thing might look like
date = moment().subtract(18, 'months').startOf('month');
if(date.day() > 1){ //check if it's Monday
//since it's not monday we add the offset
date = date.add(8-date.day(), 'days');
}
returns
_d: Mon Jul 07 2014 00:00:00 GMT-0800 (AKDT),

Get the start date and end date by passing month and year in Javascript

I wanted to know as how to get the start date and end date by passing the month name to a function like:
var myMonth="September 2015"
?
I tried this link Get first and last date but the input is different from the one that is in the link
By your question I think you want to get the particular months first date and last date.
I can suggest the following:
For first date:
var myMonth="September 2015"
myMonth = "1 "+myMonth;
var d = new Date(myMonth);
d.getDate(); // will give the start date of the month
For last date:
var myMonth="September 2015"
myMonth = "1 "+myMonth;
var checkDate = new Date(myMonth);
var d = new Date(checkDate.getFullYear(), checkDate.getMonth() + 1, 0);
d.getDate(); // this will return the last date of the month
Here is the fiddle: http://jsfiddle.net/swaprks/5z2s2myt/

MomentJS - how to select all days of the week by name?

How to sellect all same weekdays by using momentJS? Ex: All Mondays of current month. If the day is 15th day of the month, there are two Mondays in that month, from 0 to 15th day of the month. Maybe it is some kind of looping, because momenthJS should return two dates-one for first Monday and second for second Monday in the given range and so on.
Or is there any other way to do this by using any other JavaScript library?
As you said a loop can solve this problem
move 4 weeks before from the date you have e.g. if we were on the last monday of the month we move to the first monday of the month or a previous date (if we move to the previous month we can still get the correct dates by doing more iterations)
get the month of the date you have (all the dates you get should have the same month)
move forward from the initial date computed above a week each time and check if the new date has the same month as the input date
function weekdaysFromMonth (date) {
// all the weekdays previous/next to date should be
// 7 days apart and also have the same month
var month = date.get('month')
// make sure that the start date is 4 weeks before now
// we might go to the previous month but anyway we'll
// get the correct dates by doing more iterations
var start = moment(date).subtract(4 * 7, 'days')
var dates = []
for (var i = 0; i < 10; i += 1) {
start.add(7, 'days')
if (start.get('month') === month) {
dates.push(moment(start))
}
}
return dates
}
document.write(
JSON.stringify(
weekdaysFromMonth(moment()), null, ' '
)
)
<script src="http://momentjs.com/downloads/moment.js"></script>

Categories

Resources