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' })))
Related
In this date-picker, after selecting a date from the calendar, the selected date is outputted in the format dd-mm-yy, is there a way to output the date in the long format(Monday 21 February 2022.) There source of this date-picker is: https://code-boxx.com/simple-datepicker-pure-javascript-css/#sec-download
// CHOOSE A DATE
pick : (id, day) => {
// (C1) GET MONTH YEAR
let inst = picker.instances[id],
month = inst.hMonth.value,
year = inst.hYear.value;
// FORMAT & SET SELECTED DAY (DD-MM-YYYY)
if (+month<10) { month = "0" + month; }
if (+day<10) { day = "0" + day; }
inst.target.value = `${day}-${month}-${year}`;
// POPUP ONLY - CLOSE
if (inst.container === undefined) {
inst.hWrap.classList.remove("show");
}
// CALL ON PICK IF DEFINED
if (inst.onpick) { inst.onpick(); }
}
};
The date picker value will be in the format yyyy-MM-dd, you can parse this (using String.split() and pass the year, month and day to the Date() constructor.
We can then use Date.toLocaleString() to output the correct format:
function dateChanged() {
const dt = getDatePickerDate('date-input');
const options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
document.getElementById('output').innerHTML = dt.toLocaleDateString([], options);
}
function getDatePickerDate(elementId) {
const value = document.getElementById(elementId).value
const [year, month, day] = value.split('-');
return new Date(year, month - 1, day);
}
<input id='date-input' type="date" value="2022-02-21" onchange='dateChanged()'>
<p id='output'></p>
I need to increase the current date in Moscow time by 1 day every time the clock is 15:00 and more. I did it at local time, but I can’t do it according to Moscow time (UTC + 3)
function date() {
const today = new Date();
const t = today.getHours();
const dtfRU = new Intl.DateTimeFormat('ru', {
month: 'long', day: '2-digit',
});
if (t >= 15) {
today.setDate(today.getDate() + 1);
document.querySelector('.date').innerHTML = dtfRU.format(today);
} else document.querySelector('.date').innerHTML = dtfRU.format(today);
}
document.addEventListener("DOMContentLoaded", date);
I found a solution here: enter link description here I needed to do something like this:
function calcTime() {
const now = new Date();
const utc = now.getTime() + (now.getTimezoneOffset() * 60000);
const d = new Date(utc + (3600000 * 3));
const h = d.getHours();
const dtfRU = new Intl.DateTimeFormat('ru', {
month: 'long', day: '2-digit',
});
if (h >= 15) {
const newd = new Date(utc + (3600000 * 3 * 9));
document.querySelector('.date').innerHTML = dtfRU.format(newd);
} else document.querySelector('.date').innerHTML = dtfRU.format(d);
}
document.addEventListener("DOMContentLoaded", calcTime);
You can retrieve the local hour in Moscow as follows:
// Get a DateTimeFormat object for the hour in Moscow in 24-hour format
const dtf = Intl.DateTimeFormat('en', {
timeZone: 'Europe/Moscow',
hour: 'numeric',
hour12: false
});
// The above will create a format that has only the hour, so you can just use it.
const hour = +dtf.format();
console.log("hour:", hour);
Alternatively, if you decide you need more than just the hour, use formatToParts. For example:
const dtf = Intl.DateTimeFormat('en', {
timeZone: 'Europe/Moscow',
hour: 'numeric',
hour12: false,
minute: 'numeric'
});
const parts = dtf.formatToParts();
const hour = +parts.find(x => x.type === 'hour').value;
const minute = +parts.find(x => x.type === 'minute').value;
console.log("hour:", hour);
console.log("minute:", minute);
You can then use that in the rest of your code however you wish.
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
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));
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);