moments how to get the last weekday of the last month(december) - javascript

i'm following this guide Get the First Weekday of the Month with moment.js
and it works fine to get the first weekday of the first month(January)
but, when i'm trying to use the opposite. i'm getting the last weekday of the month that will be December. i try to change the add in minus and sub but not working

You can use moment-business-days for doing business days related processing. It would be much easier if you are doing more of such processing and not just this problem.
var moment = require('moment-business-days');
// Set the date for december. You can use this for any month.
// Get array of business days for the month
var businessDays=moment('01-12-2017', 'DD-MM-YYYY').monthBusinessDays();
// Get last business day from the array
var lastBusinessDay = businessDays[businessDays.length-1]._d;
console.log(lastBusinessDay);
You can see the output here or clone and edit it.
Here's the fiddle

var dateFrom = moment().subtract(1, 'months').endOf('month').format("dddd")
alert(dateFrom);
For year use this
var year = moment().subtract(1, 'months').endOf('month').get('year');
alert(year);
use this with format "dddd".
So for business weekday use "moment-business" library.
working fiddle

/*
get last day of the year and add days:
0 : if not sunday/saturday
-2 : if sunday
-1 : if saturday
*/
var eom = moment().utc().endOf('year');
eom.add((eom.day() % 6 !== 0) ? 0 : (eom.day() === 0) ? -2 : -1, 'day');
/* Testing for every last week day of the month .. */
var eom = null; /* store end-of-month */
var log = '';
var i = 0;
/* loop for all 12 months from jan - dec */
while (i < 12) {
eom = moment().utc().month(i).endOf('month');
log = eom.format('LLLL') + ' ~~~ ';
eom.add((eom.day() % 6 !== 0) ? 0 : (eom.day() === 0) ? -2 : -1, 'day');
log += eom.format('LLLL');
console.log(log);
i++;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script>

Related

How to calculate days between two date excluding weekends in angularjs? [duplicate]

This question already has answers here:
Find day difference between two dates (excluding weekend days)
(13 answers)
Closed 3 years ago.
In my application i have two date picker as start date and end date. when user choose start and end date the system will show the days between two dates but excluding the saturday and sunday. How to calculate it by using angularjs?
Does something like this work:
var startDate = new Date("01-10-2020");
var endDate = new Date("01-20-2020");
var nextDay = new Date(startDate);
var cnt = 0;
do {
/*if (nextDay.getDay() >= 1 && nextDay.getDay() <= 5) {
cnt = cnt + 1;
}*/
cnt += (nextDay.getDay() >= 1 && nextDay.getDay() <= 5) ? 1 : 0;
nextDay.setDate(nextDay.getDate() + 1);
} while (nextDay <= endDate);
console.log("Number of week days between " + startDate + " and " + endDate + " = " + cnt);
Here is the fiddler.
You don't want to do an expensive loop over every day to see whether it is Saturday or Sunday. The logic should be as follows:
Work in UTC so we don't need to worry about time zone
Calculate total number of calendar weeks. In a single calendar week, there are guaranteed to be 5 weekdays (not weekends == SAT || SUN)
Calculate the remainder of days. This will be added to the calculation later.
Determine the "finalAdjustment" by seeing if the remainder falls on weekend days.
The number of weekdays is (5 * numWeeks) + remainderDays + finalAdjust
(function() {
"use strict";
var SUN = 0;
var MON = 1;
var TUE = 2;
var WED = 3;
var THU = 4;
var FRI = 5;
var SAT = 6;
function isWeekendDay(day) {
return day === SAT || day === SUN;
}
function numberWeekDays(start, end) {
var numCalendarDays = (end - start) / 1000 / 60 / 60 / 24;
var numWeeks = Math.floor(numCalendarDays / 7);
// Potential days to add on to the number of full calendar
// weeks. This will be adjusted by "finalAdjust"
var remainderDays = numCalendarDays % 7;
// Adjustments for start and end dates being on a weekend
// ----------------------------
// Start at one because the same day should count as 1
// but number of days between same day is 0 based on
// arithmetic above.
// Change this to 0 if you don't want end date inclusive...
var finalAdjust = 1;
var startDay = start.getUTCDay();
var endDay = end.getUTCDay();
// On a weekend, so adjust by subtracting 1
if (isWeekendDay(startDay)) {
finalAdjust--;
}
// On a weekend, so adjust by subtracting 1
if (isWeekendDay(endDay)) {
finalAdjust--;
}
// This accounts for subtracting an extra weekend when starting
// at the beginning of a weekend (e.g. Saturday into Monday)
// The end day cannot also be on a weekend based on week modular division (mod 7)
if (startDay === SAT && remainderDays > 2) {
finalAdjust--;
}
// ---------------------------
// For every full calendar week there are 5 week days
// Use that number with the remainderDays and finalAdjust above
// to arrive at the answer.
var numWeekDays = (5 * numWeeks) + remainderDays + finalAdjust;
return numWeekDays;
}
// Test cases
// Assume that the start and end dates are inclusive
// 2020-01-01 to 2020-01-01 is one day
// 2020-01-01 to 2020-01-02 is two days
// ----------------------
// A Wednesdday
var start = new Date("2020-01-08");
// A Saturday
var end = new Date("2020-02-01");
// Expected answer: 18
console.log(numberWeekDays(start, end));
// A Saturday
start = new Date("2020-01-05");
// A Monday
end = new Date("2020-01-31");
// Expected answer: 20
console.log(numberWeekDays(start, end));
// Weekday to weekday Tuesday to
start = new Date("2020-01-07");
end = new Date("2020-01-16");
// Expected: 8
console.log(numberWeekDays(start, end));
// Same week: Mon-Wed
start = new Date("2020-01-06");
end = new Date("2020-01-08");
// Expected answer: 3
console.log(numberWeekDays(start, end));
// Same day
start = new Date("2020-01-08");
end = new Date("2020-01-08");
// Expect: 1
console.log(numberWeekDays(start, end));
// Weekend only
start = new Date("2020-01-04");
end = new Date("2020-01-05");
// Expect: 0;
console.log(numberWeekDays(start, end));
// ------------------
}());
As others have stated, a date library like moment is useful here because it gives you a lot of utility functions for working with dates and durations.

Determine if the date is today or is in the past using MomentJS?

Im building a mini calendar that just displays the current month, I have figured out how to map out the calendar, here is the code:
Code:
var month = moment(),
index = 0,
maxDay = month.daysInMonth(),
start = month.startOf("month"),
offset = (start.isoWeekday() - 1 + 7) % 7; // start from monday
var week = []; // holds the weeks
var days = []; // holds the days
do {
var dayIndex = index - offset;
if(dayIndex >= 0 && dayIndex < maxDay){
days.push({
number: dayIndex + 1,
isPast: null, // stuck here boolean
isToday: null // stuck here boolean
})
}
if(index % 7 === 6){
week.push(days);
console.log(week);
days = [];
if (dayIndex + 1 >= maxDay) {
break;
}
}
index += 1;
} while(true);
This works fine, the only issue Im having is to figure out if the day is today or its in the past?
the code is here also: https://jsfiddle.net/chghb3Lq/3/
Moment has isBefore, isAfter and isSame functions to compare moments and as the docs says:
If you want to limit the granularity to a unit other than milliseconds, pass the units as the second parameter.
There are a couple of things in your code that you can achieve in a simple way using momentjs instead of reimplementing by yourself:
To loop from the first day of the month until the last day you can use:
startOf('month') and endOf('month') as limit of the loop
add(1, 'day') to increment loop index
isBefore as loop condition
Use date() to get date of the month (1-31)
Use day() to get day of the week (0 => Sunday, ... 6 => Saturday); or weekday() to get day of the week locale aware.
Using these suggestions your code could be like the following:
var day = moment().startOf('month');
var endOfMonth = moment().endOf('month');
var week = [];
var month = [];
while( day.isBefore(endOfMonth) ){
week.push({
number: day.date(),
isPast: moment().isAfter(day, 'day'),
isToday: moment().isSame(day, 'day')
});
if( day.day() === 0 ){
month.push(week);
week = [];
}
day.add(1, 'day');
}
console.log(month);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
Use moment methods like isSame() , isBefore(), isSameOrBefore() etc.
They each allow setting comparison units like year month week day hour minute second
See Query Section of moment docs

Insert code based on date

Ok, I understand the basics of this, but I'm trying to set up a snippet of code that would allow me to insert HTML using jQuery's '.html' or '.append' function.
I've managed this alone, but I have to insert the code based on the seasons - a little more explanation here: I need to have a certain section of code included during the summer, one for winter, spring and so on.
Now, I know how to get the current date and I know how to use IF statements but I keep getting stuck on the format of the date that would allow me to compare it to set dates for the seasons and then have the function run for each one.
In case someone needs them here are some examples, not accurate ones of course:
Winter: January to March
Spring: March to June
Summer: June to November
Autumn: November to January
If someone could give me an example of this I would be very grateful. (I also couldn't figure out how to add more specific dates for the start and end of the seasons due to the fact some months have fewer/more days .... and also for events such as Christmas and Halloween)
var date = new Date(),
month = date.getMonth(),
date = date.getDate()m
season;
if(month <= 2 && date <= 20) { // Up to 20th March
season = "Winter";
} else if(month <= 5 && date <= 5) { // Up to 5th June
season = "Spring";
} // etc
$("#myDiv").html("It is " + season);
Updated with date example
Don't use string dates, use the Date object. It can tell you the current month which allows you to:
var month = new Date().getMonth();
if(month >= 0 && month <= 2) { // Jan ... March
} ...
Note that months start with 0 (== January) to 11 (== December)
Here's another option, a lot more complicated, but you can set the dates as requested, and check what season it.
var getSeason = function() {
var self = this;
return function(date, o) {
if (date == 'getDefaults') return self.defaults;
if (date == 'setDefaults') self.defaults = $.extend(self.defaults, o);
date = typeof date == 'string' ? new Date(date) : date;
var year = date.getFullYear(),
arr = $.map(self.defaults, function(d, key) {
var dt = new Date(year, d.slice(0,2)-1, d.slice(3,5), 0,0,0,0);
dt.setDate(dt.getDate()-1); // subtract one to get the startdate right
return {season : key, start_date : dt};
}).sort(function(a, b) {
return a.start_date.getTime() > b.start_date.getTime() ? 1 : -1;
}),
season = arr[arr.length-1].season;
$.each(arr, function(idx, itm) {
if (date > itm.start_date && arr[idx+1] != undefined && date < arr[idx+1].start_date) {
season = itm.season;
return false;
}
});
return season;
}
}
getSeason.prototype.defaults = { // start dates, (month/date)
spring : '03/01',
summer : '05/20',
fall : '08/04',
winter : '10/10'
}
You initialize a new season checker with new, like this :
var seasonChecker = new getSeason;
and then use it to check the season, you can pass a valid string or a date object :
seasonChecker( '03/20/14' ); // returns "spring"
seasonChecker( '03-20-14' ); // returns "spring"
seasonChecker( new Date('Thu Mar 20 2014 00:00:00') ); // returns "spring"
seasonChecker( new Date(1395270000000) ); // returns "spring"
You can get the default dates with :
seasonChecker('getDefaults');
or set the default dates for an instance at any time with :
seasonChecker('setDefaults', {
spring : '02/21',
summer : '03/22',
fall : '06/04',
winter : '11/01'
});
Here's a demonstration
FIDDLE

how to check a date is within current week or current month or next month in javascript?

I have some friends' birthdays and want to separate them as follows :
birthdays which fall within the current week (within remaining days of current week starting from current day).
birthdays which fall within the current month (within remaining days of current month starting from current day).
birthdays which fall within the next month.
So all I want to know how to test each date in javascript to see if it falls within the remaining days of the current week/current month/next month.
N.B: say I have those dates in m/d/Y(06/29/1990) format.
Thanks
Convert your date and current time to Date object and use it for comparison. Some dry coding:
var now = new Date()
if (
(check.getFullYear() == now.getFullYear()) &&
(check.getMonth() == now.getMonth()) &&
(check.getDate() >= now.getDate())
) {
// remanining days in current month and today. Use > if you don't need today.
}
var nextMonth = now.getMonth() + 1
var nextYear = now.getFullYear()
if (nextMonth == 12) {
nextMonth = 0
nextYear++
}
if (
(check.getFullYear() == nextYear) &&
(check.getMonth() == nextMonth)
) {
// any day in next month. Doesn't include current month remaining days.
}
var now = new Date()
now.setHours(12)
now.setMinutes(0)
now.setSeconds(0)
now.setMilliseconds(0)
var end_of_week = new Date(now.getTime() + (6 - now.getDay()) * 24*60*60*1000 )
end_of_week.setHours(23)
end_of_week.setMinutes(59)
end_of_week.setSeconds(59) // gee, bye-bye leap second
if ( check >=now && check <= end_of_week) {
// between now and end of week
}
the code Using the Parse Date is
var selecteddate = '07/29/1990';
var datestr = selecteddate.split('/');
var month = datestr[0];
var day = datestr[1];
var year = datestr[2];
var currentdate = new Date();
var cur_month = currentdate.getMonth() + 1;
var cur_day =currentdate.getDate();
var cur_year =currentdate.getFullYear();
if(cur_month==month && day >= cur_day)
{
alert("in this month");
}
else
{
alert("not in this month");
} ​

Using Javascript to automatically adjust date to 2nd Saturday of every month?

I need Javascript code for a website to automatically adjust a date. The goal is to have the code automatically adjust the following statement to be the second Saturday of every month from now until eternity:
Next membership meeting: Saturday, MONTH, DAY, YEAR 11 a.m. to noon.
Anyone have an idea? Much appreciated!
This function will get you the date object, you can pull out what you need from it:
var getMeeting = function(year, month){
var date = new Date(year, month, 1, 0, 0, 0, 0);
date.setDate(14-date.getDay());
return date;
};
alert(getMeeting(2011,5));
I didn't test but here is the basics:
//our main code
var Months = ["Jan", "Feb", "Mar", /*... you finish... */ ];
var meetingDate = getMonthlyMeeting();
document.Write( "<i>Next membership meeting:</i> Saturday, " + Months[meetingDate.getMonth()] + ", " + meetingDate.getDay() + ", " + meetingDate.getYear() + " 11 a.m. to noon.");
// call this to get the monthly meeting date
// returns a Date() object
function getMonthlyMeeting(){
var today = new Date(); //JS automatically initializes new Date()s to the current time
//first, see if today is our meeting day
var meetingDate;
var thisMonthsMeeting = getSecondTuesdayInMonth(today.getMonth(), today.getYear());
if( thisMonthsMeeting.getDay() == today.getDay() ){
// today is our meeting day!
meetingDate = today;
}
else {
if ( today.getDay() < thisMonthsMeeting.getDay() ){
// it hasn't happened this month yet
meetingDate = thisMonthsMeeting;
} else {
//this month's meeting day has already passed
if( today.getMonth() == 11 ){
// rolling over to the next year
meetingDate = getSecondTuesdayInMonth(0, today.getYear() + 1);
} else {
meetingDate = getSecondTuesdayInMonth(today.getMonth() + 1, today.getYear());
}
}
}
return meetingDate;
}
// this is a helper function to get the second tuesday in any month
// returns a Date() object
function getSecondTuesdayInMonth(var month, var year){
var saturdays = 0;
var testDay= new Date();
while( testDay.getDay() != 2 && saturdays < 2 ){
//while the day we are testing isnt tuesday (2) and we haven't found it twice
if( testDay.getDay() == 2 )
saturdays = saturdays + 1; //we found a saturday
testDay= new Date(testDay.getTime() + 86400000); //increment our day to the next day
}
//when we finish the while loop, we are on our day
return testDay;
}
So, I figure that the meat of your problem is: How do I know what the second saturday of each month is?
Not tested, but this is what I came up with:
It is abstracted for any nth day of any month.
nthDate = function(nth_week, nth_day, month){
var src_date = new Date();
src_date.setDate(1);
src_date.setMonth(month);
return ( (nth_week * 7) - src_date.getDay() ) - ( Math.abs( nth_day - 6) );
};
var cur_date = new Date();
var cur_day = cur_date.getDay();
//2 for the 2nd week of the month
//6 is the integer value for saturday (days of the week 0-6)
var nth_date = nthDate( 2, 6, cur_date.getMonth() );
if(cur_day < nth_date){
//display the upcoming date here
}else if( cur_day > nth_date){
//figure out next month's date and display that
var next_date = nthDate(2, 6, (cur_date.getMonth() +1) );
//does this deal with the case of the month being december?? not sure.
}
The 2nd week is in the range of 14 days into the month.
We can:
first subtract the offset for the day of the week that this month starts with,
then second:
we can subtract the offset for the day of the week that we are looking for.
(this needs to be the offset of days, so saturday is a 0 (zero) offset. We get this value from the absolute value of nth day minus the number of days in the week.
This gives us the date of the second saturday.
Then, because you have some ints you can do a simple compare against the values.
If we're before the second saturday, display that, if not calculate a new date for next month.
Hope that helps.

Categories