For a scheduling application, I need to display the weekdays by week numbers starting on Mondays. So far I got to:
var options = {
weekday: 'long',
year: 'numeric',
month: 'long',
day: 'numeric'
};
const weekDays = [];
for (let index = 1; index < 7; index++) {
weekDays.push(new Date(year, 0, index + (week - 1) * 7).toLocaleDateString('nl-NL', options));
}
This code displays a range of dates given by a week and year, but can't seem to get it to start on mondays. Any ideas am I missing something ?
You're assuming that January 1st of each year starts on a monday. This piece of code automatically finds the first monday of each year.
var year = 2016;
var week = 1;
var index = 1;
var options = {
weekday: 'long',
year: 'numeric',
month: 'long',
day: 'numeric'
};
var d = new Date(year, 0, index + (week - 1) * 7);
var weekday = d.getDay();
var diff = 1 - weekday;
if (diff < 0) {
diff = diff + 7;
}
d.setDate(d.getDate() + diff);
console.log(d.toLocaleString(undefined, options));
Related
How to get weekday list between two dates? I need javaScript function for that. (date-fns library function also is Ok)
as e example
getWeekDayList('2022-01-10', '2022-01-20');
function getWeekDayList(startDate, endDate){
//Output should be week days only
2022-01-10
2022-01-11
2022-01-12
2022-01-13
2022-01-14
2022-01-17
2022-01-18
2022-01-19
2022-01-20
}
You can use a for loop to loop through each date between the start and end date, then use Date.getDay to get the day of the week and ignore the dates that are not a weekday.
function getWeekDayList(startDate, endDate) {
let days = []
let end = new Date(endDate)
for (let start = new Date(startDate); start <= end; start.setDate(start.getDate() + 1)) {
let day = start.getDay();
if (day != 6 && day != 0) {
days.push(new Date(start));
}
}
return days;
}
const result = getWeekDayList('2022-01-10', '2022-01-20')
console.log(result.map(e => e.toLocaleString('en-US', {weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' })))
Suppose I have variable with datetime as,
let givenDateTime = '2021-01-29T04:22:22.148Z';
I want to get all months and year in an array from givenDateTime to currentDate.
Expected O/P : ["April 2021", "March 2021", "February 2021", "January 2021"]
For this I tried as:
let createdDate = new Date(givenDateTime);
let currentDate = new Date();
let dateAndYearList = [createdDate.toLocaleString('en', { month: 'long', year: 'numeric' })];
while (createdDate.setMonth(createdDate.getMonth() + 1) < currentDate) {
dateAndYearList.unshift(createdDate.toLocaleString('en', { month: 'long', year: 'numeric'
}));
}
But on console.log(dateAndYearList) , it gives , ** ["April 2021", "March 2021","January 2021"]**, all month from January except for February.
Can anybody tell me how can I get all the months from created month i.e. January to current month i.e. April? If any one needs any further information please do let me know.
set the day of createdDate to 1
let givenDateTime = '2021-01-29T04:22:22.148Z';
let createdDate = new Date(givenDateTime);
createdDate.setDate(1);
let currentDate = new Date();
let dateAndYearList = [createdDate.toLocaleString('en', { month: 'long', year: 'numeric' })];
while (createdDate.setMonth(createdDate.getMonth() + 1) < currentDate) {
dateAndYearList.unshift(createdDate.toLocaleString('en', { month: 'long', year: 'numeric'
}));
}
console.log(dateAndYearList)
The following script calculates me next Friday and next Sunday date.
The problem : the use of .toISOString uses UTC time. I need to change with something that outputs local time. I'm very new to javascript so I can't find the right property to use instead of .toIsostring.
What should I do ?
function nextWeekdayDate(date, day_in_week) {
var ret = new Date(date || new Date());
ret.setDate(ret.getDate() + (day_in_week - 1 - ret.getDay() + 7) % 7 + 1);
return ret;
}
let nextFriday = nextWeekdayDate(null, 5);
let followingSunday = nextWeekdayDate(nextFriday, 0);
console.log('Next Friday : ' + nextFriday.toDateString() +
'\nFollowing Sunday: ' + followingSunday.toDateString());
/* Previous code calculates next friday and next sunday dates */
var checkinf = nextWeekdayDate(null, 5);
var [yyyy, mm, dd] = nextFriday.toISOString().split('T')[0].split('-');
var checkouts = nextWeekdayDate(null, 7);
var [cyyy, cm, cd] = followingSunday.toISOString().split('T')[0].split('-');
If you worry that the date is wrong in some timezones, try normalising the time
To NOT use toISO you can do this
const [dd1, mm1, yyyy1] = nextFriday.toLocaleString('en-GB',
{ year: 'numeric', month: '2-digit', day: '2-digit' })
.split("/")
function nextWeekdayDate(date, day_in_week) {
var ret = new Date(date || new Date());
ret.setHours(15, 0, 0, 0); // normalise
ret.setDate(ret.getDate() + (day_in_week - 1 - ret.getDay() + 7) % 7 + 1);
return ret;
}
let nextFriday = nextWeekdayDate(null, 5);
let followingSunday = nextWeekdayDate(nextFriday, 0);
console.log('Next Friday : ' + nextFriday.toDateString() +
'\nFollowing Sunday: ' + followingSunday.toDateString());
/* Previous code calculates next friday and next sunday dates */
var checkinf = nextWeekdayDate(null, 5);
var [yyyy, mm, dd] = nextFriday.toISOString().split('T')[0].split('-');
var checkouts = nextWeekdayDate(null, 7);
var [cyyy, cm, cd] = followingSunday.toISOString().split('T')[0].split('-');
console.log(yyyy, mm, dd)
// not using UTC:
const [dd1, mm1, yyyy1] = nextFriday.toLocaleString('en-GB', { year: 'numeric', month: '2-digit', day: '2-digit' }).split("/")
console.log(yyyy1, mm1, dd1)
You are concerned that the [yyyy,mm,dd] is in UTC and not in current timzone?
The nextFriday is a date object. Would it work if you use the get-functions instead?
e.g.
const nextFridayYear = nextFriday.getFullYear();
// get month is zero index based, i have added one
const nextFridayMonth = (nextFriday.getMonth() + 1).toString()
.padStart(2, '0');
const nextFridayDay = today.getDate().toString()
.padStart(2, '0');
This question already has answers here:
How do I format a date in JavaScript?
(68 answers)
Closed 2 years ago.
I'm working on making a webpage that displays the next date for the Food Pantry. It happens on the second Friday of the month. I grabbed this current code from this question and I think I was able to modifiy it to fit my needs. However, I would like it to display in a 'April, 10th' format instead of '04/10/2020'. I have an extremely basic grasp of Javascript so if you explain it like I'm five would be helpful.
Also, if the second Friday is the current day, it would be great if it could say Today.
Thank you!
Date.prototype.nextsecondFriday = function (){
// Load the month.
var target = new Date(this.getFullYear(), this.getMonth(), 1, 0, 0, 0);
var today = new Date();
// Check to see if the 1st is on a Friday.
var isFriday = (target.getDay() == 1);
// Jump ahead two weeks from the 1st, and move back the appropriate number of days to reach the preceding Friday.
// i.e. If the 1st is a Thursday, we would move back three days.
var targetDate = 12 - (target.getDay() - 1);
// Quick adjustment if the 1st is a Friday.
if (isFriday) targetDate -= 4;
// Move to the second Friday in the month.
target.setDate(targetDate);
// Second Friday is before today's date, so find the second Friday next month.
if (today > target) {
//return "<em>" + target.toLocaleDateString() + " is in the past...</em>";
target.setMonth(target.getMonth() + 1);
return target.nextsecondFriday();
}
// Format and return string date of second Friday.
return target.toLocaleDateString();
}
var secondFridayDateString = new Date().nextsecondFriday();
document.getElementById("dynamicdate").innerHTML = secondFridayDateString;
<p>Our next food pantry is <span id="dynamicdate">Second Friday</span>.</p>
The below code find the second friday for any Date()
Date.prototype.nextsecondFriday = function() {
// get second firday for given month and year
const secondFriday = (year, month) => {
// first day of the month
let date = new Date(year, month, 1);
let dayDifference = 5 - date.getDay();
// get second friday of the month
if (dayDifference < 0) {
date.setDate(date.getDate() + (14 + (-1 * dayDifference)));
} else if (dayDifference >= 0) {
date.setDate(date.getDate() + 7 + dayDifference);
}
return date;
};
// format date to "April 10th"
const formatDate = (date) => {
const months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
const month = months[date.getMonth()];
const day = date.getDate();
let suffix = 'th';
const j = day % 10,
k = day % 100;
if (j == 1 && k != 11) {
suffix = "st";
} else if (j == 2 && k != 12) {
suffix = "nd";
} else if (j == 3 && k != 13) {
suffix = "rd";
}
return `${month} ${day}${suffix}`;
};
let date = this;
let closestSecondSaturday;
do {
let secondFridayOfThisMonth = secondFriday(date.getFullYear(), date.getMonth());
if (secondFridayOfThisMonth.getDate() === date.getDate()) {
closestSecondSaturday = "Today";
} else if (secondFridayOfThisMonth.getDate() >= date.getDate()) {
closestSecondSaturday = formatDate(secondFridayOfThisMonth);
} else {
// if current date has crossed the second friday, move to the next month
date.setMonth(date.getMonth() + 1);
}
} while (!closestSecondSaturday)
return closestSecondSaturday;
};
// sample call
document.write(new Date().nextsecondFriday());
Try new Intl.DateTimeFormat('en-US', options).format(target)
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat
Date.prototype.nextsecondFriday = function (){
// Load the month.
var target = new Date(this.getFullYear(), this.getMonth(), 1, 0, 0, 0);
var today = new Date();
// Check to see if the 1st is on a Friday.
var isFriday = (target.getDay() == 1);
// Jump ahead two weeks from the 1st, and move back the appropriate number of days to reach the preceding Friday.
// i.e. If the 1st is a Thursday, we would move back three days.
var targetDate = 12 - (target.getDay() - 1);
// Quick adjustment if the 1st is a Friday.
if (isFriday) targetDate -= 4;
// Move to the second Friday in the month.
target.setDate(targetDate);
// Second Friday is before today's date, so find the second Friday next month.
if (today > target) {
//return "<em>" + target.toLocaleDateString() + " is in the past...</em>";
target.setMonth(target.getMonth() + 1);
return target.nextsecondFriday();
}
let options = { year: 'numeric', month: 'long', day: 'numeric' };
// Format and return string date of second Friday.
return new Intl.DateTimeFormat('en-US', options).format(target);
}
var secondFridayDateString = new Date().nextsecondFriday();
document.getElementById("dynamicdate").innerHTML = secondFridayDateString;
<p>Our next food pantry is <span id="dynamicdate">Second Friday</span>.</p>
I would modify the nextsecondFriday function to return the date object instead of a formatted string (just drop the toLocaleDateString() call).
Then write another function formatDate which receives a date and returns a formatted string.
Then call nextsecondFriday to get the date and format it usingformatDate.
The code for formatting (the formatDate function), if you require that specific format (the colon and the 'th' etc), would probably be something like:
const event = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));
const monthOptions = { month: 'long' };
const dayOptions = { day: 'numeric' };
const formattedDate = event.toLocaleDateString('en-US', monthOptions) + ', ' + event.toLocaleDateString('en-US', dayOptions));
// then check event.getDay() and append 'st', 'nd', 'rd' or 'th' to formattedDate as needed
But if you can go with another format then just a single call to toLocaleDateString could be enough - check toLocaleDateString documentation on MDN for details.
See toDateString
you just have to change this statement
return target.toDateString();
options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
secondFridayDateString.toLocaleDateString("en-us", options)
you need to set the format, check that.
you can play with this in the console just doing:
let date = new Date()
options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
date.toLocaleDateString("en-us", options) //set your locale as you want i.e. es-ar or any locale
I want to calculate the difference between a moment (itemMoment) and now (nowMoment) defined by weekday, hour and minute. If the itemMoment is before nowMoment (diff < 0) I want to add one week and calculate the difference again, but the addition of a week (week: week + 1 in my code )somehow doesn't change the difference and I still get a negative difference.
It's the first time I use the moment.js library so may be I don't get it how to use it correctly. Would be great if an experienced used could help.
var now = moment();
var year = now.year();
var week = now.week();
var weekday = now.weekday();
var hour = now.hour();
var minute = now.minute();
var itemMoment = moment({
day: item.weekday,
hour: item.hour,
minute: item.minute
});
var nowMoment = moment({
day: weekday,
hour: hour,
minute: minute
});
if (itemMoment.diff(nowMoment) > 0) {
item.date = moment({
year: year,
week: week,
weekday: item.weekday,
hour: item.hour,
minute: item.minute
});
diff = itemMoment.diff(nowMoment);
}
else {
if (week == 51) {
week = -1;
year = year + 1
}
item.date = moment({
year: year,
week: week + 1,
weekday: item.weekday,
hour: item.hour,
minute: item.minute
});
diff = item.date.diff(now);
you can just do comparison using isBefore() or isAfter(). http://momentjs.com/docs/#/query/
if (itemMoment.isBefore(nowMoment)) {
Then you can do manipulation like so: http://momentjs.com/docs/#/manipulating/
item.date = itemMoment.add('weeks', 1);