I have a model in my database that contains an array called "AvailableDays" [0...6]. 0 = Sunday & 6 = Saturday. I am looking to convert this day number of the week to the date of day in the current week.
For example, this is the logic broken down
Retrieve the list of available days (const availableDays = [0,2,4,6])
Get the current DATE (const today = new Date('2021-08-20');)
Covert day numbers to dates (output =['15-08-2021', '17-08-2021', '19-08-2021', '21-08-2021'])
What you can do is get the day-of-the-week from the given Date instance and work out the offset from your available day.
Then subtract that offset in days from the given date to produce your result.
const transformDate = (date, day) => {
const offset = date.getDay() - day
const d = new Date(date)
d.setDate(d.getDate() - offset)
return d
}
const availableDays = [0,2,4,6]
const today = new Date("2021-08-20")
console.log(availableDays.map(day => transformDate(today, day)))
Was able to solve this myself. I am now able to wrap this into a availableDates.map() and return an array of dates using the below logic.
var availableDay = 0
var d = new Date(),
day = d.getDay(), // 0 ... 6
calcAvailableDay = day-availableDay,
diff = d.getDate() - calcAvailableDay,
output = new Date(d.setDate(diff));
console.log(output)
You can generate all the days in weeks and then get the dates using availableDays.
const getWeekDays = (current) => {
current.setDate((current.getDate() - current.getDay() - 1));
return Array.from({ length: 7 }, (_, i) => {
current.setDate(current.getDate() + 1)
return new Date(current).toLocaleDateString('en-CA');
});
},
today = new Date('2021-08-20'),
weekDays = getWeekDays(today),
availableDays = [0, 2, 4, 6],
availableDates = availableDays.map(day => weekDays[day]);
console.log(availableDates);
JavaScript getDay method returns the day of the week for the specified date according to local time, where 0 represents Sunday.
So what you have to do is connect this index with your availableDays values.
Logic
Get current date, month, year and the index of todays date.
Loop through the availableDays array, and create new dates with the difference between the current day calculated with getDay value and the day value specified in your array.
Make use of some logic to reperesent those date object in specified format. I took support from this post to format your date string.
const availableDays = [0,2,4,6];
const today = new Date();
const currentDay = today.getDay();
const currentDate = today.getDate();
const currentMonth = today.getMonth();
const currentYear = today.getFullYear();
formatDateToString = (date) => String(date.getDate()).padStart(2, '0') + '-' + String(date.getMonth() + 1).padStart(2, '0') + '-' + date.getFullYear();
const output = availableDays.map((day) => formatDateToString(new Date(currentYear, currentMonth, currentDate - (currentDay - day))));
console.log(output);
Related
Here's the code that I have right now:
const moment = require('moment')
const m = moment
const currDay = m().format('D')
const dayOfWeek = m().format('dddd')
const daysInMonth = m().daysInMonth()
const startOfMonth = moment().startOf('month').format('YYYY-MM-DD hh:mm');
const endOfMonth = moment().endOf('month').format('YYYY-MM-DD hh:mm');
I need to create a calendar row where the first item would be the todays date, and the rest of the calendar items would be the whatever amount of days are left depending on the current month so I could render each day in between in my HTML with Vue.
Example: Wed 8, Thu 9, Fri 10 ... Fri 31.
I think the OP is tripped up on the common mistake of formatting prematurely. format is good to see an intermediate result, but doing so produces a string that's no good for additional calculation.
Try to handle date objects only. Convert to strings only when you must: (a) presenting to a human reader, or (b) serializing for storage or transmission.
Working without formatting...
const daysRemainingThisMonth = moment().endOf('month').diff(moment(), 'days');
console.log(`There are ${daysRemainingThisMonth} days remaining this month`)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
Just as a POJS equivalent, if you have a function to return the last day of the month, you can use that and just get the difference between the two dates, e.g.
function getMonthEnd(date = new Date()) {
return new Date(date.getFullYear(), date.getMonth() + 1, 0);
}
function getMonthDaysLeft(date = new Date()) {
return getMonthEnd(date).getDate() - date.getDate();
}
let d = new Date();
console.log(`There are ${getMonthDaysLeft(d)} days left in ${d.toLocaleString('en',{month:'long'})}.`);
To get a list/array of the days remaining, just loop over a date, adding 1 day at a time, and write the dates in the required format into the list:
function getMonthDaysLeftAsList(date = new Date()) {
let d = new Date(+date);
// Formatter
let f = new Intl.DateTimeFormat('en',{
day: 'numeric',
month: 'short'
});
let m = d.getMonth();
let dayList = [];
while (d.getMonth() == m) {
dayList.push(f.format(d));
d.setDate(d.getDate() + 1);
}
return dayList;
}
console.log(getMonthDaysLeftAsList());
I need to display the current week of the month in the following format in react-native:
(Week 2: 05.10 - 11.10) (example of week 2 of current month)
What would be some suggestions as how to achieve this? I know that there are packages such as momentjs to build this but would like some examples of how to achieve this
any help is appreciated!
You can adapt the code below. I say "adapt" because you haven't specified when your week starts (Sunday or Monday?) or how you want to count which week within the month it is (i.e. is week #1 the first full week? The code below assumes so).
Anyway, by clicking the "Run Code Snippet" button, you'll see what it does, including some intermediate steps, which are there to illustrate where the values are coming from, and therefore what you might want to "adapt" for your needs.
//get the first day of week and last day of week, borrowed from https://stackoverflow.com/a/64529257/1024832 above
const getWeek = (date = new Date()) => {
const dayIndex = date.getDay();
const diffToLastMonday = (dayIndex !== 0) ? dayIndex - 1 : 6;
const dateOfMonday = new Date(date.setDate(date.getDate() - diffToLastMonday));
const dateOfSunday = new Date(date.setDate(dateOfMonday.getDate() + 6));
return [dateOfMonday, dateOfSunday];
}
//get week number w/in the month, adapted from https://stackoverflow.com/a/57120367/1024832
const getWeekNumber = () => {
let todaysDate = moment(moment.now());
let endOfLastMonth = moment(todaysDate).startOf('month').subtract(1, 'week');
let weekOfMonth = todaysDate.diff(endOfLastMonth, 'weeks');
return weekOfMonth;
}
//capture/log some steps along the way
const [Monday, Sunday] = getWeek();
console.log("First/Last of week as Date Objects: ", Monday, Sunday);
let Monday_formatted = moment(Monday).format("DD.MM");
let Sunday_formatted = moment(Sunday).format("DD.MM");
console.log(Monday_formatted, "-", Sunday_formatted);
console.log("Week #:", getWeekNumber());
//set the DIV content
document.getElementById("datehere").innerText = `(Week ${getWeekNumber()}): ${Monday_formatted} - ${Sunday_formatted}`;
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
<div id="datehere"></div>
Here's an answer as a function which returns the current week's Monday and Sunday in an array:
getWeek = (date = new Date()) => {
const dayIndex = date.getDay();
const diffToLastMonday = (dayIndex !== 0) ? dayIndex - 1 : 6;
const dateOfMonday = new Date(date.setDate(date.getDate() - diffToLastMonday));
const dateOfSunday = new Date(date.setDate(dateOfMonday.getDate() + 6));
return [dateOfMonday, dateOfSunday];
}
const [Monday, Sunday] = getWeek();
console.log(Monday, Sunday);
The response is two valid date objects. You can also pass a date object for the function to get Monday and Sunday of that date's week (e.g. getWeek(new Date(0));
But when you want to parse those dates, you should gain better knowledge of Date Object.
I have question about getting full two years from the current date. So what i did id get the current month using the new date function and used the for loop to print each of the month. But, i cant really get it to work.... I will post the code that i did below. I would be really appreciate it if anyone can tell me the logic or better way of doing it.
For example: if today current date is august it store into an array from 8 / 2020 9/ 2020 ..... 12/ 2020, 1/2021 and goes to another year to 8/2022.
var d = new Date();
var year = d.getFullYear();
var dateStr;
var currentYear;
var storeMonthYear = [];
for(var i = 1; i <= 24; i++){
dateStr = d.getMonth() + i
currentYear = year;
if(dateStr > "12"){
dateStr = dateStr - 12
// currentYear = year;
// if(currentYear){
// }
storeMonthYear[i] = dateStr + "/" + (currentYear + 1);
}
else if(dateStr > "24"){
storeMonthYear[i] = dateStr + "/" + (currentYear + 1);
}
else{
storeMonthYear[i] = dateStr + "/" + currentYear;
}
storeMonthYear[i] = d.getMonth() + i
}
export const settlementPeriod = [
{
MonthYearFirstRow1: storeMonthYear[1],
MonthYearFirstRow2: storeMonthYear[2],
MonthYearFirstRow3: storeMonthYear[3],
MonthYearFirstRow4: storeMonthYear[4],
MonthYearFirstRow5: storeMonthYear[5],
MonthYearFirstRow6: storeMonthYear[6],
MonthYearFirstRow7: storeMonthYear[7],
MonthYearFirstRow8: storeMonthYear[8],
MonthYearFirstRow9: storeMonthYear[9],
MonthYearFirstRow10: storeMonthYear[10],
MonthYearFirstRow11: storeMonthYear[11],
MonthYearFirstRow12: storeMonthYear[12],
MonthYearSecondRow13: storeMonthYear[13],
MonthYearSecondRow14: storeMonthYear[14],
MonthYearSecondRow15: storeMonthYear[15],
MonthYearSecondRow16: storeMonthYear[16],
MonthYearSecondRow17: storeMonthYear[17],
MonthYearSecondRow18: storeMonthYear[18],
MonthYearSecondRow19: storeMonthYear[19],
MonthYearSecondRow20: storeMonthYear[20],
MonthYearSecondRow21: storeMonthYear[21],
MonthYearSecondRow22: storeMonthYear[22],
MonthYearSecondRow23: storeMonthYear[23],
MonthYearSecondRow24: storeMonthYear[24]
},
];
Create the date from today, get the month and year. Iterate from 0 to 24 for now till in 24 months. If month is 12 than set month to 0 and increment the year. Push the new datestring. Increment the month for the next step.
Note: Beacsue JS counts months form 0-11 you had to add for the datestring 1 for the month and make the change of year at 12 and not 13.
let date = new Date();
let year = date.getFullYear();
let month = date.getMonth();
let res=[];
for (let i=0; i<=24; i++) {
if (month===12) {
month = 0;
year++;
}
res.push(month+1 + '/' + year);
month++;
}
console.log(res);
Here you go, you get an array of strings like "8/2020","9/2020" etc from starting month to the last month including both( in total 25 months).
If you don't want to include last month just delete +1 from for loop condition.
let currentDate = new Date();
let settlementPeriod = [];
let numberOfMonths = 24;
for(let i=0;i<numberOfMonths+1;i++){
settlementPeriod.push(currentDate.getMonth()+1+"/"+currentDate.getFullYear()); //We add current date objects attributes to the array
currentDate = new Date(currentDate.setMonth(currentDate.getMonth()+1)); //Every time we add one month to it
}
console.log(settlementPeriod);
There are a couple of things that stick out in your code sample:
You're comparing strings and numbers (e.g. dateStr > "12"). This will lead to some weird bugs and is one of JS's most easily misused "features". Avoid it where possible.
You increment the year when you reach 12 months from now, rather than when you reach the next January
You're overwriting your strings with this line storeMonthYear[i] = d.getMonth() + i so your array is a bunch of numbers rather than date strings like you expect
Here's a code sample that I think does what you're expecting:
function next24Months() {
const today = new Date()
let year = today.getFullYear()
let monthIndex = today.getMonth()
let dates = []
while (dates.length < 24) {
dates.push(`${monthIndex + 1}/${year}`)
// increment the month, and if we're past December,
// we need to set the year forward and the month back
// to January
if (++monthIndex > 11) {
monthIndex = 0
year++
}
}
return dates
}
In general, when you're dealing with dates, you're probably better off using a library like Moment.js - dates/times are one of the most difficult programming concepts.
While #Ognjen 's answer is correct it's also a bit waseful if your date never escapes its function.
You don't need a new date every time:
function getPeriods(firstMonth, numPers){
var d = new Date(firstMonth.getTime()); // clone the start to leave firstMonth alone
d.setDate(1); // fix after #RobG
var pers = [];
var m;
for(var i = 0; i< numPers; i++){
m = d.getMonth();
pers.push(`${m+ 1}/${d.getFullYear()}`)
d.setMonth(m + 1); // JS dates automatically roll over. You can do this with d.setDate() as well and when you assign 28, 29, 31 or 32 the month and year roll over automatically
}
return pers;
}
I've a variable that has value of date in YYYYMM format. For example:
var givenDate = "201704"
How can I find out the last day of the given month and append to it. For example,
//last day of 2017 04 (April) is 30th so append value to givenDate + lastDate;
//that will be 20170430
var newFullGivenDate = "20170430";
const date = "201704";
const year = parseInt(date.substring(0, 4));
const month= parseInt(date.substring(4, 6));
const lastDay = (new Date(year, month, 0)).getUTCDate();
const newFullGivenDate = date + lastDay;
console.log(newFullGivenDate);
var givenDate = "201704";
var month = givenDate.substring(4, givenDate.length); // retrieves 04
var year = givenDate.substring(0, 4); // retrieves 2017
var d = new Date(year, month, 0);
alert(d.getDate());
Reference: MDN
To achieve expected result, use below option
last day of month - new Date(year,month ,0)
var givenDate = "201704";
var currDate = new Date(givenDate.substr(0,3),givenDate.substr(4) ,0)
var newFullGivenDate = givenDate + currDate.getDate();
console.log(newFullGivenDate)
Codepen URL for reference - https://codepen.io/nagasai/pen/OmgZMW
I would break it down into two functions:
// Get last day from year and month
let lastDayOf = (year, month) => (new Date(year, month, 0)).getDate();
// Add last day to string only if input is correct
let addLastDay = (input) => {
// In case you pass number (201705) instead of string ("201705")
if (Number.isInteger(input)) input = input.toString();
// Check if input is in correct format - 6 digit string
if (typeof input !== "string" || !input.match(/^\d{6}$/)) {
return input; // You can implement desired behavour here. I just return what came
}
const year = input.substr(0, 4);
const month = input.substr(4, 2);
return input + lastDayOf(year, month);
}
// Tests
console.assert(addLastDay("201704"), "20170430");
console.assert(addLastDay("201702"), "20170228");
console.assert(addLastDay("201202"), "20120229");
console.assert(addLastDay(201705), "20170531");
console.assert(addLastDay(20170), 20170); // Wrong input
// Interactive example
document.getElementsByTagName('button')[0].addEventListener('click', () => {
let input = document.getElementsByTagName('input')[0];
input.value = addLastDay(input.value);
});
<input type="text" value="201704"><button>Calculate</button>
If you are using moment js you can yry this:
var date = moment(newFullGivenDate ).format('YYYYMMDD');
date = date.add(-1 * parseInt(date.format('DD')), 'days').add(1, '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);