How to get the date of a specific day in javascript? - javascript

I have a diferent number of days
example (1=monday,2=tuesday.......)
and i need to return the date o this day in the current week
For example: if i send number 3 to my function, in this current week, today is sunday 23 , and i need that my function give me the date of the day 3 in this week, in this case the wednesday day was june-19 .
other example i pass the number 5 to my function the function return me the date of the day 5 this week (friday)= june-21 (2019/06/21)
something like that
let currentDate = new Date().toISOString().slice(0, 10)

The strategy is fairly straight forward:
new Date() gets you the current date
The getDay method returns the day number of the date's day of the week
The getDate method returns the day number of the date's day of the month
The setDate method sets the day number of the date's day of the month
So you get the current date, subtract the current day number, then add the day number you want to the date. This will also wrap to previous and following months, e.g.
/* Given a week day number, return the date for that
* day in the current week.
*
* #param {number} dayNumber - number of day in week.
* If 0, returns Sunday at start of week
* If 7, returns Sunday at end of week
* Otherwise 1 Mon, 2 Tue, etc.
* If not an integer in range 0 to 7 returns undefined
* #returns {number|undefined} date of supplied day number
*/
function getDateForDayInWeek(dayNumber) {
dayNumber = Number(dayNumber);
// Validate input
if (dayNumber < 0 ||
dayNumber > 7 ||
parseInt(dayNumber) != dayNumber) {
return; // undefined
}
let d = new Date();
d.setDate(d.getDate() - d.getDay() + dayNumber);
return d.getDate();
}
// Examples
console.log('Today is ' +
new Date().toLocaleString(undefined, {
month:'long', weekday:'long', day:'numeric'
})
);
// Sample values
[0, // Sunday at start of week
3, // Wednesday
7, // Sunday end of week
23, -2, 2.4 // All invalid, return undefined
].forEach(
n => console.log(n + ':' + getDateForDayInWeek(n))
);
You might want the function to return a Date, then you can do more with it, including just getting the date, but also the month and day name, etc.

Related

Can I add number of days to the (dayoftheweek) to get another day?

I have a date and from that I find the dayoftheweek . Lets say the day I found is Tuesday . I have a variable that has duration . Lets say the duration is 5 days . Will I be able to add 5 to Tuesday and get Saturday as the answer . Tuesday should be considered as day 1 and saturday as day 5.
date = 04/13/2021 #in mm/dd/yyyy
dayoftheweek = GetDayOfWeek(date) #Tuesday
duration = 5
Is this correct?
finaldayoftheweek = dayoftheweek + 5 # I want to get Saturday as answer
If not how do I do that ?
If you want Saturday, add 4 days.
/*
* Obtain the day of the week, tht will occur a number of days after the
* provided {#code dateString}.<p>
* #param {String} dateString - format: mm/dd/yyyy
* #param {Numer} addDays - days to add to date
* #return {String} returns the day of week in its 'long' format.
*/
const getDayOfWeek = (dateString, addDays) => {
const [month, date, year] = dateString.split('/').map(v => parseInt(v, 10));
const d = new Date(year, month - 1, date);
d.setDate(d.getDate() + addDays);
return d.toLocaleDateString('en-US', { weekday: 'long' });
}
console.log(getDayOfWeek('04/13/2021', 4)); // Saturday
If all you want to do is add a number of days to a day of week and get another day of week then use a modulo operation.
#!/usr/bin/env python3
DAYS_IN_A_WEEK = 7
start_day_of_week = 2 # Tuesday
number_of_days_to_add = 10 # or 3, 17, 24, 31, etc...
end_day_of_week = (start_day_of_week + number_of_days_to_add) % DAYS_IN_A_WEEK
print(end_day_of_week) # 5 (Saturday)
You can try this in Python, however since you want Saturday, you should add 4:
import datetime
date = datetime.date(2021, 4, 13)
dayoftheweek = date.strftime("%A") #Tuesday
duration = 4 #Since you mentioned you wanted Saturday
finaldate = date + datetime.timedelta(days= duration)
finaldayoftheweek = finaldayoftheweek.strftime("%A") #Saturday

Number of days in the months corresponding to selected dates

I need to find the number of days as days from months chosen between two dates. For example, if I choose date1 as January 1,2021 and date2 as March 1, 2021, then I need to get the total number of days in January, February and March.
Output=
Number of days in january + Number of days in february + Number of days in march = 31+28+31
What I tried:
const getDiff=(selectedDate1,selectedDate2)=>{
console.log('Date check',moment(selectedDate1).daysInMonth(),moment(new Date()).daysInMonth())
if(moment(selectedDate1).daysInMonth() - moment(selectedDate2).daysInMonth() ===0){
return Number(moment(selectedDate1).daysInMonth())
}else{
return Number(moment(selectedDate1).daysInMonth())+Number(moment(selectedDate2).daysInMonth())
}
}
But with this code, i am getting only the sum of days of the selected dates, ie. only Number of days in January + Number of days in March
Using moment.js, you just get the difference between start of the start month and end of the end month in days plus 1 (because the end of month won't include the last day and adding 1 is simpler than going to the start of the following month), e.g.
function wholeMonthDays(d1, d2) {
let diff = moment(d2).endOf('month').diff(moment(d1).startOf('month'),'days') + 1;
return diff;
}
let start = new Date(2021,0,21);
let end = new Date(2021,2,11);
console.log(wholeMonthDays(start, end)); // 90
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
Alternatively you can go to the start of the month after end to get the difference:
function wholeMonthDays(d1, d2) {
let start = moment(d1).startOf('month');
let end = moment(d2).startOf('month').add(1, 'month');
let diff = end.diff(start, 'days');
return diff;
}
let start = new Date(2021, 0, 21);
let end = new Date(2021, 2, 11);
console.log(wholeMonthDays(start, end)); // 90
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
I've set the dates to during the month to show that it adds the "days in months" rather than just the difference between the two dates.
If you actually want an array of the total days in each month, just set the start to the end of the month, get the date, add one month, set to the end of the month, etc. until you've gone past the end month.
A couple of things:
Remember that Months in Java and JavaScript are (moronically) 0-based. So month 1 is February
To get the number of days in a month you can use a Date object and go to the first of the next month, then substract 1 day, then call getDay.
The time between two dates in milliseconds is
var d1 = ...;
var d2 = ...;
var duration = Math.abs(d2.getTime() - d1.getTime());
You can then divide duration by milliseconds (1000), seconds (60), minutes (60) etc to get the timespan in the unites you'd
The simplest way would be:
// 'lo' and 'hi' could be of type Date or numbers coming from Date.getTime()
const daysBetween = (lo, hi) => {
const oneDayInMilliseconds
= 1000 // one sec has 1000 millis
* 3600 // one hour has 3600 seconds
* 24; // one day has 24 hours
return (hi - lo) / oneDayInMilliseconds;
}

How to create date object from next day of week, hh:mm and utc offset

I have these 4 input values.
Day of week: integer 0-6 (0: Sunday, 1: Monday, ... 6: Saturday)
Hours: integer 0-24
Minutes: integer 0-60
UTC offset: integer -12 - 14
With above input values, I want to create date object.
Day of week can be either of next week or this week according to current time.
Eg.
Lets assume current time is 10:00 Mon 2021.
And day of week is 1 (Monday) and Hours is 12 then this is today.
Other case, if hours is less than 10 then it would be next Monday(next week).
I have tried moment and date in javascript but I got stuck here.
Please advise me to make this createDate function
var createDate(var dow, var hh, var mm, var utc){
//return date object
}
For the date part consider the following:
function createDate(dow, hh, mm, utc) {
const date_today = moment();
const dow_today = date_today.day();
var days_dif = dow - dow_today;
if (days_dif < 0) {
console.log(moment().add(7, 'd').format('YYYY/MM/DD'));
} else {
console.log(moment().add(days_dif, 'd').format('YYYY/MM/DD'));
}
}
You'll have to add more if statements for hours and minutes if date_dif is equal to 0, otherwise just add hours and minutes to the date in the else statement.

Get the current week using JavaScript without additional libraries ? [SO examples are broken]

I built a calendar control and was adding the week numbers as a final touch, and encountered a problem with every script example I could find on SO and outside of SO (most of which one has copied from the other).
The issue is that when dates fall in partial months, the week calculation seems to mess up and either continue counting when it is the same week in a new month, or it thinks the last full week in a previous month is the same week number as the first full new week in the following month.
Following is a visual demonstration of one of the libraries (they all have their inaccuracies as they generally base their week calculation off a fixed number and build from there) :
You can view the codepen here as the project is rather complex, I have the Date.prototype.getWeek function at the start to play with this easier. Feel free to swap in any code from the samples found here on SO as they all end up funking out on some months.
Some of the calculations used :
Show week number with Javascript?
Date get week number for custom week start day
w3resource.com ISO86901
epoch calendar - getting ISO week
Get week of year in JavaScript like in PHP
When running the most current example (2017) from "Get week of year in JavaScript like in PHP", the week returned right now is 42. When you look on my calendar, the week in October right now is showing as 42 which is correct according to here https://www.epochconverter.com/weeks/2018.
Given the example, there are full weeks sharing the same week number - so I don't see how 42 can even be accurate.
Date.prototype.getWeek = function (dowOffset) {
/*getWeek() was developed by Nick Baicoianu at MeanFreePath: http://www.epoch-calendar.com */
dowOffset = typeof(dowOffset) == 'int' ? dowOffset : 0; //default dowOffset to zero
var newYear = new Date(this.getFullYear(),0,1);
var day = newYear.getDay() - dowOffset; //the day of week the year begins on
day = (day >= 0 ? day : day + 7);
var daynum = Math.floor((this.getTime() - newYear.getTime() -
(this.getTimezoneOffset()-newYear.getTimezoneOffset())*60000)/86400000) + 1;
var weeknum;
//if the year starts before the middle of a week
if(day < 4) {
weeknum = Math.floor((daynum+day-1)/7) + 1;
if(weeknum > 52) {
nYear = new Date(this.getFullYear() + 1,0,1);
nday = nYear.getDay() - dowOffset;
nday = nday >= 0 ? nday : nday + 7;
/*if the next year starts before the middle of
the week, it is week #1 of that year*/
weeknum = nday < 4 ? 1 : 53;
}
}
else {
weeknum = Math.floor((daynum+day-1)/7);
}
return weeknum;
};
Here is some code (also tried this) that is Sunday specific (see near the bottom). I am also pasting the relevant snip here :
/* For a given date, get the ISO week number
*
* Based on information at:
*
* http://www.merlyn.demon.co.uk/weekcalc.htm#WNR
*
* Algorithm is to find nearest thursday, it's year
* is the year of the week number. Then get weeks
* between that date and the first day of that year.
*
* Note that dates in one year can be weeks of previous
* or next year, overlap is up to 3 days.
*
* e.g. 2014/12/29 is Monday in week 1 of 2015
* 2012/1/1 is Sunday in week 52 of 2011
*/
function getWeekNumber(d) {
// Copy date so don't modify original
d = new Date(Date.UTC(d.getFullYear(), d.getMonth(), d.getDate()));
// Set to nearest Thursday: current date + 4 - current day number
// Make Sunday's day number 7
d.setUTCDate(d.getUTCDate() + 4 - (d.getUTCDay()||7));
// Get first day of year
var yearStart = new Date(Date.UTC(d.getUTCFullYear(),0,1));
// Calculate full weeks to nearest Thursday
var weekNo = Math.ceil(( ( (d - yearStart) / 86400000) + 1)/7);
// Return array of year and week number
return [d.getUTCFullYear(), weekNo];
}
The algorithm is to use the week number of the following Saturday. So get the following Saturday, then use it's year for the 1st of Jan. If it's not a Sunday, go to the previous Sunday. Then get the number of weeks from there. It might sound a bit convoluted, but it's only a few lines of code. Most of the following is helpers for playing.
Hopefully the comments are sufficient, getWeekNumber returns an array of [year, weekNumber]. Tested against the Mac OS X Calendar, which seems to use the same week numbering. Please test thoroughly, particularly around daylight saving change over.
/* Get week number in year based on:
* - week starts on Sunday
* - week number and year is that of the next Saturday,
* or current date if it's Saturday
* 1st week of 2011 starts on Sunday 26 December, 2010
* 1st week of 2017 starts on Sunday 1 January, 2017
*
* Calculations use UTC to avoid daylight saving issues.
*
* #param {Date} date - date to get week number of
* #returns {number[]} year and week number
*/
function getWeekNumber(date) {
// Copy date as UTC to avoid DST
var d = new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()));
// Shift to the following Saturday to get the year
d.setUTCDate(d.getUTCDate() + 6 - d.getUTCDay());
// Get the first day of the year
var yearStart = new Date(Date.UTC(d.getUTCFullYear(), 0, 1));
yearStart.setUTCDate(yearStart.getUTCDate() - yearStart.getUTCDay());
// Get difference between yearStart and d in milliseconds
// Reduce to whole weeks
return [d.getUTCFullYear(), (Math.ceil((d - yearStart) / 6.048e8))];
}
// Helper to format dates
function fDate(d) {
var opts = {weekday:'short',month:'short',day:'numeric',year:'numeric'};
return d.toLocaleString(undefined, opts);
}
// Parse yyyy-mm-dd as local
function pDate(s){
var b = (s+'').split(/\D/);
var d = new Date(b[0],b[1]-1,b[2]);
return d.getMonth() == b[1]-1? d : new Date(NaN);
}
// Handle button click
function doButtonClick(){
var d = pDate(document.getElementById('inp0').value);
var span = document.getElementById('weekNumber');
if (isNaN(d)) {
span.textContent = 'Invalid date';
} else {
let [y,w] = getWeekNumber(d);
span.textContent = `${fDate(d)} is in week ${w} of ${y}`;
}
}
Date:<input id="inp0" placeholder="yyyy-mm-dd">
<button type="button" onclick="doButtonClick()">Get week number</button><br>
<span id="weekNumber"></span>

How to select first day and last day of the week when we select any date in dojox.calendar.?

I am using a custom dojox.calendar. currently if I select any date I am able to get the date. Now,How to select first day and last day of the week when we select any date in dojox.calendar.?
Here is a small function that, given a Date object and week day number, returns the previous day of the same week day number (Sunday = 0, Monday = 1, …, Saturday = 6).
function getPreviousDay(date, day) {
var d = new Date(+date);
d.setDate(d.getDate() - ((7 + d.getDay() - day) % 7));
return d;
}
console.log(getPreviousDay(new Date(2013,11,24), 2)); // Tue 17-Dec-2013
If the Date is a Tuesday and the week day number is 2, it will return a copy of the supplied Date. This can be used to build functions that, given a Date, return the previous Sunday and next Saturday:
// If date is Sunday, return a copy of date (default for getPreviousDay)
// Otherwise, get previous Sunday
function getPreviousSunday(date) {
var d = getPreviousDay(date, 0);
return d;
}
// If date is Saturday, return a copy of date
// Otherwise, get previous Saturday and add 7 days
function getNextSaturday(date) {
if (date.getDay() == 6) {
return new Date(+date);
}
var d = getPreviousDay(date, 6);
d.setDate(d.getDate() + 7);
return d;
}
var d = new Date(2013,11,21);
console.log(
d + '\n' +
getPreviousSunday(d) + '\n' +
getNextSaturday(d)
);
/*
Sat 21-Dec-2013
Sun 15-Dec-2013
Sat 21-Dec-2013
*/
Those values can then be used to select a date range in the calendar.
I use new Date(+date) to copy dates because otherwise in the years 0 to 99, IE will assume 1900 to 1999 and mess up the copy. While it's unlikely you'll want to use dates in this range (pretty pointless really) it makes me feel better knowing that it will "work" if you do.
IE does this because if a Date object is passed to the Date constructor, it is first converted to a string, then the string parsed to create a Date object. IE incorrectly parses its own string for years 0 to 99. Using + converts the date to a time value, which is treated correctly by the Date constructor everywhere (as far as I know).

Categories

Resources