how can I get every day of the month except Friday with Moment.js? - reactjs

Can someone help me ? I'm trying to get all the days of the month except Friday to disable all this days in a date picker but I can't figure out, how to proceed. I'm looking for the solution for a while now...
So I need an array of Moment to disable them in the date picker.
Here is the date picker.
Thank's for your time and sorry for my bad english !

Without extending moment you can try:
let fridaysInMonth = [];
const monthDate = moment().startOf('month');
const daysInMonth = monthDate.daysInMonth();
for(let i=0; i< daysInMonth; i++){
if (monthDate.day() === 5){
const currFridayDate = moment(monthDate);
fridaysInMonth.push(currFridayDate);
}
monthDate.add(1, 'day');
}
Or extend moment and use moment-range:
const month = moment();
const range = moment().range(moment(month).startOf('month'), moment(month).endOf('month'));
const days = range.by('days');
const fridaysInMonth = days.filter(currDay => currDay.day() === 5);

Related

Why Would Date Change give me This Error Code?

I have this code that connect to an API. It uses the current month and year to do a query of data. When the month was Aug, and it used the number 8 for ${month}, all worked perfectly. Now that it is Sept, and it uses 9 for ${month}, it returns "request failed with status 400". But if I set it back to 8, it works perfectly again. Any idea why this would be the case?
Getting Date and Setting Path based on date:
const date = new Date();
console.log(date);
const year = date.getFullYear();
let month = date.getMonth() + 1;
const path = `/v2/reports/time/team?from=${year}0${month}01&to=${year}0${month}31`;
Then this call, worked perfectly throughout the month of Aug, when month was 8. Now in Sept, month changes to 9, and I get status 400. Why?
Variables for API call:
const https = require('https');
const options = {
protocol: "https:",
hostname: "api.xxxxx.com",
path: path,
headers: {
"User-Agent": "PPR Profile",
"Authorization": "Bearer " + "xxxxxxxxx",
"Harvest-Account-ID": "xxxxxxxx"
}
}
Actual Call:
When I manually set month to 8, console log shows exactly the data I want. When manually set month to 9, i get the error 400 code.
let teamBillableData = [];
let teamMemberBillableAmount = 0;
let teamMemberIndex = 0;
https.get(options, (res) => {
const { statusCode } = res;
if (statusCode !== 200) {
console.error(`Request failed with status: ${statusCode}`);
return;
}
res.setEncoding('utf8');
let rawData = '';
res.on('data', (chunk) => { rawData += chunk; });
res.on('end', () => {
try {
const parsedData = JSON.parse(rawData);
for (let i = 0; i < parsedData.results.length; i++){
console.log(`${parsedData.results[i].user_name} billable: $${parsedData.results[i].billable_amount}`);
}
console.log(parsedData.results);
As Dave hints at, your API may require valid dates. There are only 30 days in September and your end date is set to 31 for all requests.
You will also need to fix where the code appends 0 to the month as it will create three digit months for October, November, and December.

How to dynamically disable days in react datepicker

I am using React DatePicker .I want to disable days in date picker. I am able to doing so by passing day number like below so Monday Tuesday and Saturday get's disabled.But how do I achieve this dynamically? I am able to form array like this
var notAvailableDays=[1,2,6] // which should disable these days. How do I return this at once?
const isWeekday = (date) => {
const day = date.getDay(date);
return day !== 1 && day !== 2 && day !== 6;
}
;
You can do an array lookup like this
const notAvailableDays = [1,2,6];
const isDisabled = (date) => {
const day = date.getDay(date);
return notAvailableDays.includes(day);
}

Display current date calendar react?

I am building a calendar, it has 53 weeks from (12-30-2019 -> 03-01-2021). How when the app first loads it display current date.
// the function display dates
export default function RenderDates(props) {
const dates_ = [];
const startDate = moment('12-29-2019', 'MM-DD-YYYY');
// display date in week
for(let i = 1; i <= 53*7; i++) {
dates_.push(
<Date>
<ContentDate>
<ShortDate>{moment.weekdaysShort()[i%7]}</ShortDate>
<span>{startDate.add(1,'days').get('Date')}</span>
</ContentDate>
</Date>
)
}
return dates_;
}
demo: https://codesandbox.io/s/github/Kalipts/scroll_calendar?file=/src/components/RenderDates.js
You can assign unique id to every date box and then focus today's box
https://codesandbox.io/s/quirky-leavitt-w2x3w
export default function RenderDates(props) {
const dates_ = [];
const startDate = moment("12-29-2019", "MM-DD-YYYY");
useEffect(() => {
const today = moment().format("YYYY-MM-DD");
console.log('today', today);
const node = document.getElementById(today);
if (node) {
node.setAttribute("tabindex", "-1");
node.focus();
node.removeAttribute("tabindex");
}
}, []);
for (let i = 1; i <= 53 * 7; i++) {
const date = startDate.add(1, "days");
dates_.push(
<Date id={date.format("YYYY-MM-DD")}>
<ContentDate>
<ShortDate>{moment.weekdaysShort()[i % 7]}</ShortDate>
<span>{date.get("Date")}</span>
</ContentDate>
</Date>
);
}
return dates_;
}
I just changed a bit your codesandbox to make it work and here is the link: https://codesandbox.io/s/vibrant-worker-b2xhq?file=/src/App.js
Basically what I did was:
On your RenderDates component I check for the current date and added an id to the Date component if that date was the current one.
On App component (It could be on RenderDates component) I added a useEffect to run once the component is mounted that getElementById using the id on date and scrollIntoView.
It is very simple and works well! :)

How to calculate hour between start date and end date excluding the weekend in AngularJS

In my application i have start datetime picker and end datetime picker. any idea how to calculate hours between two dates excluding weekend in AngularJS.
Here is a function that will count only business workday hours for you using moment.js library -:
function calculateWorkDays(start, end) {
if (moment(end, "YYYY-MM-DD").isBefore(start, "YYYY-MM-DD")) {
return null;
}
var duration = moment.duration(
moment(end, "YYYY-MM-DD").diff(moment(start, "YYYY-MM-DD"))
);
var hours = duration.asHours();
var days = moment.duration(
moment(end, "YYYY-MM-DD").diff(moment(start, "YYYY-MM-DD"))
)._data.days;
for (let i = 0; i < days; i++) {
if (
[6, 7].includes(
moment(start, "YYYY-MM-DD")
.add(i, "days")
.day()
)
) {
hours -= 24;
}
}
console.log(hours);
return hours;
}

JS getDate comparison doesn't work on certain dates

I'm working on a simple calendar on my website, and I'm trying to accomplish the following:
Today's date should be on a dark background color (css class: nyt)
Future days should appear on a lighter background color (css class: tuleva)
Past days should appear with 0.5 opacity (css class: menny)
This is the javascript code that I'm using:
$(function() {
var date = new Date(),
currentDate = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" +
date.getDate();
$(".kalenteripv").each(function() {
var specifiedDate = $(this).data('date');
if (specifiedDate == currentDate) {
$(this).addClass('nyt');} // this day
else if (currentDate > specifiedDate) {
$(this).addClass('menny');} // past days
else {$(this).addClass('tuleva');} // future days
});
});
Today (2017-12-2), for some reason the calendar is showing the dates 10-19 on 0.5 opacity, so the code is adding the "menny" or past dates' css class to those dates, which it obviously shouldn't do. I tried already to write the dates with two digits (e.g. 2017-12-02), but when I do that, the whole code stops working.
Here's an image to clarify the problem with dates 10-19
Any suggestions? It must be some kind of simple mistake that I'm making, but I really can't figure it out myself. I hope I explained the problem clear enough.
Here's the fiddle that shows the problem.
https://jsfiddle.net/vfy1bfnz/
Thank you in advance!
$(function pvmr() {
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
if(dd<10) {
dd = '0'+dd
}
if(mm<10) {
mm = '0'+mm
}
today = yyyy + "-" + mm + "-" + dd;
$(".kalenteripv").each(function pvmr() {
var specifiedDate = $(this).data('date');
if (specifiedDate == today) {
$(this).addClass('nyt');
} else if (today < specifiedDate) {
$(this).addClass('tuleva');
} else if (today > specifiedDate) {
$(this).addClass('menny');
}
});
});
Solved it! I thought I should leave the answer here in case someone needs the code some day.

Resources