I am trying to get all day (input by me) in a specific end date (input by me).
example :
I have day 1 and I have end date 10/12/2021
beginning from new Date():
output must be: 1/10/2021 1/11/2021 1/12/2021
day 1 for this month is not included because we are in day 20 and day 20 > day 1
Same, I chose day 20 (example) and end date = 19/12/2021 day 20 in end date not included because day 20 > end date day
I have already tried that as simple using if condition, but not great work because in this case, I have 8 conditions!
I want a simple code that works for this situation.
Hope that is what you wanted. You can simplify it more if you want.
const getRemainingDates = function(beginningDay, endDate){
const today = new Date()
const [endDateDay,endDateMonth,endDateYear] = endDate.split("/");
const remainingMonth = endDateMonth - (today.getMonth()+1);
for(let i = 0; i <= remainingMonth; i++){
if(i === 0){
if(beginningDay>today.getDate() && beginningDay>endDateDay){
console.log(`${beginningDay}/${today.getMonth()+1+i}/${today.getFullYear()}`)
}
else {}
}
if(i !== 0)console.log(`${beginningDay}/${today.getMonth()+1+i}/${today.getFullYear()}`)
}
}
getRemainingDates(21,"12/12/2021");
console.log()
getRemainingDates(1,"12/12/2021");
Related
I'm trying to prep a table which would have a header be an array of months/year. So the table would look roughly like such:
month1/year, month2/year, month3/year, etc....
field1:
field2:
field3:
The particular months/years are based upon a start and end date provided by a user. Based on some answers here, I have the logic working, however I hit a snag. By the way I've gone about getting the month (using getMonth()), it returns it as the index (so 0 for Jan, etc.). My first thought was just to +1, but clearly I then run into an issue with December -> January. My javascript skills are weak, so my only thought is to write in an if statement and adjust the final array after the fact.
Here's what I have so far:
function dateRange(startDate, endDate, steps = 1) {
const dateArray = [];
let currentDate = new Date(startDate);
while (currentDate <= new Date(endDate)) {
dateArray.push(new Date(currentDate));
// Use UTC date to prevent problems with time zones and DST
currentDate.setUTCDate(currentDate.getUTCDate() + steps);
}
console.log("dateArray: ", dateArray)
const monthSet = dateArray.map(i => `${i.getMonth()}/${i.getFullYear()}`)
const header = [...new Set(monthSet)]
return header;
}
const dates = dateRange(isStart, isEnd);
console.log(dates);
It's not entirely clear what you're asking, sorry. But if you're wondering how to increment the month index without getting numbers like 13, 14, etc., you can use the modulo operator:
1 % 12 === 1;
2 % 12 === 2;
3 % 12 === 3;
10 % 12 === 10;
12 % 12 === 0;
13 % 12 === 1;
You should be safe simply adding 1 to .getMonth(), since that function will only ever yield values 0 though 11.
I would like to show the date in an element on a web page, then once a week on a Saturday it will update to that Saturdays date, if the Saturday of the week hasn't been reached it will simply display the previous Saturdays date until the next Saturday.
I am able to get the date and to extract the day of the week, therefore i can identify when it is a Saturday. I have attempted to include an IF statement that will update the text when Saturday arrives. That seems to be working however I do not know how to keep it displaying the previous Saturdays date until it next updates?
HTML:
<div id="date">
</div>
JS:
var date = new Date(); //Gets current date
var day = date.getDay(); //Isolates what day it is
if (day === 6) {
document.getElementById("date").innerHTML = date;
} else {
//keep the previous saturday somehow?
}
I have a JSFiddle with the code I have been practising with:
https://jsfiddle.net/Lime26/8txryo3k/13/
Seems to be working what I have so far, not sure how to get it to continue displaying the previous Saturdays date.
On a side note: to test this I have been manually changing the day integer between 0 and 6 to determine if it is working which it is.
I am attempting to set the date by entering 6, then I will enter a different number and in theory I would like it to not change (to check it I am watching the seconds and minutes expecting them to remain 'frozen') and then when I enter 6 again I expect it to change to the most current time.
this solution no need if condition:
var date = new Date(); //Gets current date
var day = date.getDay(); //Isolates what day it is
date.setDate(date.getDate() - (day+1) % 7 );
// day = 0 , (day+1) % 7 = 1
// day = 1 , (day+1) % 7 = 2
// .
// .
// day = 6 , (day+1) % 7 = 0 /here is sat
document.getElementById("date").innerHTML = date;
<div id="date"></div>
This uses the MomentJS library. The library has additional formatting options, this is just one example.
const saturday = moment().day(6);
const saturdayFormatted = moment(saturday).format("ddd MM/DD/YYYY");
const prevSaturday = moment().day(13);
const prevSaturdayFormatted = moment(prevSaturday ).format("ddd MM/DD/YYYY");
const e1 = document.getElementById("id1").innerHTML = saturday;
const e2 = document.getElementById("id2").innerHTML = saturdayFormatted
const e3 = document.getElementById("id3").innerHTML = prevSaturday;
const e4 = document.getElementById("id4").innerHTML = prevSaturdayFormatted;
<script src="https://momentjs.com/downloads/moment.js"></script>
This Saturday (with and without formatting)
<ul>
<li id="id1">one</li>
<li id="id2">two</li>
</ul>
Next Saturday (with and without formatting)
<ul>
<li id="id3">one</li>
<li id="id4">two</li>
</ul>
This will do the trick.
I'm essentially converting the current time into a Unix timestamp (epoch time) and subtracting the number of days that have passed in seconds. This will give you back the same time but the date turned back.
var date = new Date();
var day = date.getDay();
if (day === 6) {
document.getElementById("date").innerHTML = date;
} else {
date.setTime(date.getTime() - (86400 * ((day % 6) + 1)));
document.getElementById("date").innerHTML = date;
}
<span id="date"></span>
Javascript- How to get an exact date after exactly 'X' years from a given date (birth date), say 'YYYY/MM/DD'
If you want to calculate age from date, here is the code you need:
var birthDate = getDateFromTextbox();
var today = new Date();
var age = today.getFullYear() - birthDate.getFullYear();
var m = today.getMonth() - birthDate.getMonth();
if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
age--;
}
If you want calculate year from 2 dates, replace
var today = new Date();
by
var today = yourDate();
If you want add year to Date try it:
date.setYear(date.getFullYear + 7);
A trivial version would be
function addYearsToDate(date, years) {
return +date.slice(0, 4)+years + date.slice(4);
}
Here, the +date.slice(0,4) makes a number out of the first four characters of the date, to which we add the number of years, then concatenate that with the remainder of the input date.
> addYearsToDate('1953/04/18', 62)
< "2015/04/18"
You will need to special-case Feb. 29.
This assumes you want the input and output in string form YYYY/MM/DD. For more sophisticated date manipulation, consider using a library like moment which would allow you to do things like
moment('1953/04/18').add(62, 'years')
I am using Moment.js and it is great. The problem I have now is that I can't figure out how to get the week of the month a certain date is. I can only find "week of year" in the Moment js docs. For example, if I choose today's date (2/12/2014), I would like to know that this date is in the second week of this month of february and consequently, it is the second wednesday of the month. Any ideas?
EDIT:
I guess some clarification is necessary. What I need most is the nth number of a certain day in a month. For example, (from the comments) Feb 1, 2014 would be the first Saturday of the month. Feb 3, 2014 would be the first Monday of the month even though it is "technically" the second week of the month. Basically, exactly how google calendar's repeat function classifies days.
It seems that moment.js does not have the method that implements the functionality that you are looking for.
However, you can find the nth number of a certain day of the week in a month is using the Math.ceil of the date / 7
For example:
var firstFeb2014 = moment("2014-02-01"); //saturday
var day = firstFeb2014.day(); //6 = saturday
var nthOfMoth = Math.ceil(firstFeb2014.date() / 7); //1
var eightFeb2014 = moment("2014-02-08"); //saturday, the next one
console.log( Math.ceil(eightFeb2014.date() / 7) ); //prints 2, as expected
It looks like this is the number you are looking for, as demonstrated by the following test
function test(mJsDate){
var str = mJsDate.toLocaleString().substring(0, 3) +
" number " + Math.ceil(mJsDate.date() / 7) +
" of the month";
return str;
}
for(var i = 1; i <= 31; i++) {
var dayStr = "2014-01-"+ i;
console.log(dayStr + " " + test(moment(dayStr)) );
}
//examples from the console:
//2014-01-8 Wed number 2 of the month
//2014-01-13 Mon number 2 of the month
//2014-01-20 Mon number 3 of the month
//2014-01-27 Mon number 4 of the month
//2014-01-29 Wed number 5 of the month
When calculating the week of the month based on a given date, you have to take the offset into account. Not all months start on the first day of the week.
If you want to take this offset into account, you can use something something like the following if you are using moment.
function weekOfMonth (input = moment()) {
const firstDayOfMonth = input.clone().startOf('month');
const firstDayOfWeek = firstDayOfMonth.clone().startOf('week');
const offset = firstDayOfMonth.diff(firstDayOfWeek, 'days');
return Math.ceil((input.date() + offset) / 7);
}
Simple using moment.js
function week_of_month(date) {
prefixes = [1,2,3,4,5];
return prefixes[0 | moment(date).date() / 7]
}
This library adds the function moment.weekMonth()
https://github.com/c-trimm/moment-recur
I made some modifications based on feedback.
let weeks = moment().weeks() - moment().startOf('month').weeks() + 1;
weeks = (weeks + 52) % 52;
On days passing through the next year, the week value will be negative so I had to add 52.
What about something like:
weekOfCurrentMonth = (moment().week() - (moment().month()*4));
This takes the current week of the year, and subtracts it by the 4 times the number of previous months. Which should give you the week of the current month
I think the answer to this question will be helpful, even though it doesn't use moment.js as requested:
Get week of the month
function countWeekdayOccurrencesInMonth(date) {
var m = moment(date),
weekDay = m.day(),
yearDay = m.dayOfYear(),
count = 0;
m.startOf('month');
while (m.dayOfYear() <= yearDay) {
if (m.day() == weekDay) {
count++;
}
m.add('days', 1);
}
return count;
}
There is a problem with #Daniel Earwicker answer.
I was using his function in my application and the while loop was infinite because of the following situation:
I was trying to figure out which week of december (2016) was the day 31.
the first day of december was day 336 of the year. The last day of december was day 366 of the year.
Problem here: When it was day 366 (31 of december, last day of the year) the code added another day to this date. But with another day added it would be day 1 of january of 2017. Therefore the loop never ended.
while (m.dayOfYear() <= yearDay) {
if (m.day() == weekDay) {
count++;
}
m.add('days', 1);
}
I added the following lines to the code so the problem would be fixed:
function countWeekdayOccurrencesInMonth(date) {
var m = moment(date),
weekDay = m.day(),
yearDay = m.dayOfYear(),
year = m.year(),
count = 0;
m.startOf('month');
while (m.dayOfYear() <= yearDay && m.year() == year) {
if (m.day() == weekDay) {
count++;
}
m.add('days', 1);
}
return count;
}
It verifies if it is still in the same year of the date being veryfied
Here's Robin Malfait's solution implemented with the lightweight library date-fns
import {
differenceInDays,
startOfMonth,
startOfWeek,
getDate
} from 'date-fns'
const weekOfMonth = function (date) {
const firstDayOfMonth = startOfMonth(date)
const firstDayOfWeek = startOfWeek(firstDayOfMonth)
const offset = differenceInDays(firstDayOfMonth, firstDayOfWeek)
return Math.ceil((getDate(date) + offset) / 7)
}
export default weekOfMonth
I'd do the following:
let todaysDate = moment(moment.now());
let endOfLastMonth = moment(get(this, 'todaysDate')).startOf('month').subtract(1, 'week');
let weekOfMonth = todaysDate.diff(endOfLastMonth, 'weeks');
That gets todaysDate and the endOfLastMonth and then uses Moment's built-in diff() method to compute the current month's week number.
It's not built-in, but basically you can subtract the week number of the start of the month from the week number of the date in question.
function weekOfMonth(m) {
return m.week() - moment(m).startOf('month').week() + 1;
}
Credit goes to code by original author, give him a star if it helped you.
How about this?
const moment = require("moment");
// Generate Week Number of The Month From Moment Date
function getWeekOfMonth(input = moment()) {
let dayOfInput = input.clone().day(); // Saunday is 0 and Saturday is 6
let diffToNextWeek = 7 - dayOfInput;
let nextWeekStartDate = input.date() + diffToNextWeek;
return Math.ceil((nextWeekStartDate) / 7);
}
Simple code, but has been working for me.
const weekOfTheMonth = (myMomentDate) => {
const startDay = moment(myMomentDate).startOf('week');
const day = parseInt(startDay.format('DD'),10);
if(day > 28){
return 5;
}
if((day > 21) && (day <= 28) ){
return 4;
}
if((day > 14) && (day <= 21) ){
return 3;
}
if((day > 7) && (day <= 14) ){
return 2;
}
return 1;
}
If I have a date coming into a function, how can I tell if it's a weekend day?
var dayOfWeek = yourDateObject.getDay();
var isWeekend = (dayOfWeek === 6) || (dayOfWeek === 0); // 6 = Saturday, 0 = Sunday
var isWeekend = yourDateObject.getDay()%6==0;
Short and sweet.
var isWeekend = ([0,6].indexOf(new Date().getDay()) != -1);
I tried the Correct answer and it worked for certain locales but not for all:
In momentjs Docs: weekday
The number returned depends on the locale initialWeekDay, so Monday = 0 | Sunday = 6
So I change the logic to check for the actual DayString('Sunday')
const weekday = momentObject.format('dddd'); // Monday ... Sunday
const isWeekend = weekday === 'Sunday' || weekday === 'Saturday';
This way you are Locale independent.
Update 2020
There are now multiple ways to achieve this.
1) Using the day method to get the days from 0-6:
const day = yourDateObject.day();
// or const day = yourDateObject.get('day');
const isWeekend = (day === 6 || day === 0); // 6 = Saturday, 0 = Sunday
2) Using the isoWeekday method to get the days from 1-7:
const day = yourDateObject.isoWeekday();
// or const day = yourDateObject.get('isoWeekday');
const isWeekend = (day === 6 || day === 7); // 6 = Saturday, 7 = Sunday
I've tested most of the answers here and there's always some issue with the Timezone, Locale, or when start of the week is either Sunday or Monday.
Below is one which I find is more secure, since it relies on the name of the weekday and on the en locale.
let startDate = start.clone(),
endDate = end.clone();
let days = 0;
do {
const weekday = startDate.locale('en').format('dddd'); // Monday ... Sunday
if (weekday !== 'Sunday' && weekday !== 'Saturday') days++;
} while (startDate.add(1, 'days').diff(endDate) <= 0);
return days;
In the current version, you should use
var day = yourDateObject.day();
var isWeekend = (day === 6) || (day === 0); // 6 = Saturday, 0 = Sunday
Use .getDay() method on the Date object to get the day.
Check if it is 6 (Saturday) or 0 (Sunday)
var givenDate = new Date('2020-07-11');
var day = givenDate.getDay();
var isWeekend = (day === 6) || (day === 0) ? 'It's weekend': 'It's working day';
console.log(isWeekend);
var d = new Date();
var n = d.getDay();
if( n == 6 )
console.log("Its weekend!!");
else
console.log("Its not weekend");
The following outputs a boolean whether a date object is during «opening» hours, excluding weekend days, and excluding nightly hours between 23H00 and 9H00, while taking into account the client time zone offset.
Of course this does not handle special cases like holidays, but not far to ;)
let t = new Date(Date.now()) // Example Date object
let zoneshift = t.getTimezoneOffset() / 60
let isopen = ([0,6].indexOf(t.getUTCDay()) === -1) && (23 + zoneshift < t.getUTCHours() === t.getUTCHours() < 9 + zoneshift)
// Are we open?
console.log(isopen)
<b>We are open all days between 9am and 11pm.<br>
Closing the weekend.</b><br><hr>
Are we open now?
Alternatively, to get the day of the week as a locale Human string, we can use:
let t = new Date(Date.now()) // Example Date object
console.log(
new Intl.DateTimeFormat('en-US', { weekday: 'long'}).format(t) ,
new Intl.DateTimeFormat('fr-FR', { weekday: 'long'}).format(t) ,
new Intl.DateTimeFormat('ru-RU', { weekday: 'long'}).format(t)
)
Beware new Intl.DateTimeFormat is slow inside loops, a simple associative array runs way faster:
console.log(
["Sun","Mon","Tue","Wed","Thu","Fri","Sat"][new Date(Date.now()).getDay()]
)
Simply add 1 before modulo
var isWeekend = (yourDateObject.getDay() + 1) % 7 == 0;