I have an array of dates
date_array = ["date1", "date2", "date3"]
I would like to print
Tuesday: Yes
Wednesday: No
Thursday: No
Friday: Yes
Saturday: No
Sunday: Yes
where Yes and No depends on whether there is a date in date_array on this weekday in the current week and the order of the weekdays should start from today's weekday.
I am using moment where the weekday number can be formatted with e, so I get the number of today's weekday with moment().format('e'). Alternatively, it could be with moment().day() where sunday=0.
I guess I could do something like
// Existing dates
var dates = [moment(), moment().add(3, 'days'), moment().add(5, 'days')]
// All weekdays to print
var weekdays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
// Reorder
var today_weekday = moment().day()
var weekdays_reordered = weekdays.splice(today_weekday).concat(weekdays)
// Print
weekdays_reordered.map((weekday, i) => {
console.log(weekday + ': ' + (dates.some(date => date.day() === i) ? 'Yes' : 'No'));
});
<script src="https://momentjs.com/downloads/moment.min.js"></script>
But I'm not sure how exactly to make it work.
If I understood correctly, you need to print every day from current day until the end of the week, i.e. Sunday? Then, you need to set today_weekday as moment().day() - 1 (because of the indices), and then exit the loop when you get to Monday (changed it from map() to a for(), because you can't break out of map). Lastly, compare the date formated to dddd (the weekday name) to the current weekday element in the loop. Something like this:
var dates = [moment(), moment().add(4, 'days'), moment().add(5, 'days')]
// All weekdays to print
var weekdays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
// Reorder
var today_weekday = moment().day() - 1;
var weekdays_reordered = weekdays.splice(today_weekday).concat(weekdays)
for(var i = 0; i < weekdays_reordered.length; i++) {
var weekday = weekdays_reordered[i];
if (weekday === "Monday" && i !== 0) break;
console.log(weekday + ': ' + (dates.some(date => date.format("dddd") === weekday) ? 'Yes' : 'No'));
}
<script src="https://momentjs.com/downloads/moment.js"></script>
Assuming you have an array of dates and not moment objects, you can create a date for today then check if the same date is in the array. Then step through the days of the week. Testing for date equality is a little tricky but if they are all created for say 00:00:00 then you can just check the time value.
var base = new Date();
base.setHours(0,0,0,0);
var seed = new Date(+base);
// Array of dates for today, today + 2 days, today + 4 days
var dates = [new Date(seed),
new Date(seed.setDate(seed.getDate() + 2)),
new Date(seed.setDate(seed.getDate() + 2))
];
// Test 7 days, starting from today
for (var i=7; i; --i) {
// Get weekday name in host default language
var s = base.toLocaleString(undefined, {weekday:'long'}) + ': ';
// See if there's a matching date
s += dates.find(d=>+d == +base)? 'Yes':'No';
// Add 1 to the date
base.setDate(base.getDate() + 1);
// Do something with the result
console.log(s);
}
The above requires Array.prototype.find, there's a polyfill on MDN if required. You may need to define a different comparison (predicate) function if you want to compare only date without the time.
Related
I am brand new with javascript and I am struggling a lot. I am doing school work to learn javascript. My first end task is how to ask current day of the week. I will explain.
Request the day of the week via JavaScript. So the computer date, not through a prompt.
Create an array: dayNames. This already contains the names of the days.
Write the name of the day in the document via JS.
If it is a weekday, also write:
It's a workday, so get to work.
If it is a weekend day, write:
It's the weekend, break.
So the result is eg.
Today is “Thursday”.
It's a workday, so get to work.
let daynames = ["maandag", "dinsdag", "woensdag", "donderdag","vrijdag", "zaterdag", "zondag"];
if(daynames == daynames.getDay()){
print ("It's a workday")
}
else(daynames == daynames.getDay()) {
print("It's weekendday")
}
document.write(`<p>Today is ${daynames}</p>`);
the only thing I am strunggling with is ask the current day throu an array that has the weekdays and weekend. I know it's probally with an IF and ELSE but I got no idea how.
const dayNames = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
const today = new Date();
const dayOfWeek = today.getDay(); // 0 = Sunday, 1 = Monday, etc.
const isWeekend = dayOfWeek === 0 || dayOfWeek === 6;
const message = `Today is ${dayNames[dayOfWeek]}. ${isWeekend ? "It's the weekend, break." : "It's a workday, so get to work."}`;
document.write(message);
To get the current day, you should use
Date.prototype.getDay()
This method will return An integer number, between 0 and 6, corresponding to the day of the week for the given date, according to local time: 0 for Sunday, 1 for Monday, 2 for Tuesday, and so on.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getDay
Because the method returns 0 for Sunday, it is easier to put Sunday as the first item in the array.
let daynames = ["zondag", "maandag", "dinsdag", "woensdag", "donderdag","vrijdag", "zaterdag"];
const today = new Date().getDay()
//prepare the string to output
let output = ""
// if today is 0 meaning Sunday or 6 meaning Saturday, it is the weekend
//else it is a weekday
if(today === 0 || today === 6){
output = `Today is ${daynames[today]}, it is the weekend.`
}
else{
output = `Today is ${daynames[today]}, it is a weekday.`
}
document.write(output)
I want to get the week names ( sunday, monday, tuesday... ) and number of days based on the month and year...
daysInMonth(month, year) {
return new Date(year, month, 0).getDate();
}
let dys = this.daysInMonth(this.selected_from.getMonth() + 1, selected_year);
for (let a = 1; a <= dys; a++) {
console.log(a, 'a')
}
console.log(dys, 'dys');
By using this code i can get the number of days, but how to get the week names ?
Maybe something like this:
getDayNames(year: number, month: number) {
var days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
var daysInMonth = new Date(year, month, 0).getDate();
for (let i = 1; i <= daysInMonth; i++) {
var d = new Date(year, month, i);
var dayName = days[d.getDay()];
console.log(i + ' ' + dayName);
}
}
EDIT
Since moths are declared as 0-11 and not like 1-12 I have edited code so you can enter 1 for january, 2 for february and so...
getDayNames(year: number, month: number) {
var days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
var daysInMonth = new Date(year, month, 0).getDate();
for (let i = 1; i <= daysInMonth; i++) {
var d = new Date(year, month - 1, i);
var dayName = days[d.getDay()];
console.log(i + ' ' + dayName);
}
}
Use moment.js for such* date operations.
Here's how to get the days names by a month and an year, using moment.js
const getDayNames = (month, year) => {
const daysInMonth = moment(`${month}-01-${year}`, 'MM-DD-YYYY').daysInMonth()
const names = []
for (let i = 1; i <= daysInMonth; i++) {
let date = moment(`${month}-${i}-${year}`, 'MM-DD-YYYY')
let dayName = date.format('dddd')
names.push(`${dayName} - ${date.format('MM-DD-YYYY')}`)
}
return names
}
console.log(getDayNames(5, 2018))
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.1/moment.min.js"></script>
* Should we use an external library?
As always, here we can give you very generalized solution, without knowing the big picture (the context). It's on your own to weight - should or should not use a date library. If your app relies on complex dates operations - therefore it will be better to use one for sure.
According to your case (without knowing the context), it's controversial should or should not. It's not a complex functionality, but personally I'll prefer using it for the following reasons:
As you can see in the code snippet, moment.js give us the week day names, and easily you can enable localization / internationalization for your users.
You operate with moment.js API, which is much cleaner and imperative than Date() API, that will reduce the risk of getting things wrong.
When you have complex date operations, then it's always a good decision to use a date library, instead of writing your own functions, because there're a lot of complexities that you have to manage and consider by yourself (at a given point of time).
For example:
You want to support internationalization for the day names (translate the day name, according the user's language).
Dates manipulations (Add / Substract days).
Dates formatting.
And many other cases (hidden on a first sign)
Be careful and please don't reinvent the wheel, especially for complex date operations! :)
Credits:
Get dates in a month
Get date name
function myFunction() {
var d = new Date();
var n = d.getDay();
var day = "";
switch(n) {
case 0:
day = "Sunday";
break;
case 1:
day = "Monday";
break;
case 2:
day = "Tuesday";
break;
case 3:
day = "Wednesday";
break;
case 4:
day = "Thursday";
break;
case 5:
day = "Friday";
break;
case 6:
day = "Saturday";
break;
default:
// do something
break;
}
document.getElementById("demo").innerHTML = day;
}
Refer : https://www.w3schools.com/jsref/jsref_getday.asp
I wrote this function that creates a list of moment objects for each day of the month.
Lines can be optimized but kept it simple for clarity.
// function that gets all the days in a month with the corresponding arguments passed in
// Year, Month arguments are specified by the user, pass in the year in the month to find out the total amout of days in that month.
getDaysArrayByMonth(year,month){
// adding one to month because when you call moment.month() it returns 0-11 months instead of 1-12
const monthNum = month + 1;
// create moment object with formatted string
const year_month_string = monthNum.toString()+"-"+year.toString();
const FirstDayofMonth = moment(year_month_string,"MM-YYYY");
// find the number of days in the month from the moment object
var daysInMonth = FirstDayofMonth.daysInMonth();
// arr which will store all days in the month
var daysArr = [];
// create dayint variable to increment day of the month
var dayInt = 1;
// create string for creating moment object, will modify it in a loop to access all days of that month
var curDayofMonthString = "0"+dayInt.toString()+"-"+monthNum.toString()+"-"+year.toString();
// create moment obj with curDayofMonthString
var curDayofMonth = moment(curDayofMonthString,"DD-MM-YYYY");
// loop for total number of days in month to append all days to daysArr
while(daysInMonth){
// append day
daysArr.push(curDayofMonth);
// inc day and format string depending if day is doble digits or not
dayInt++;
if(dayInt > 9){
curDayofMonthString = dayInt.toString()+"-"+monthNum.toString()+"-"+year.toString();
}else{
curDayofMonthString = "0"+dayInt.toString()+"-"+monthNum.toString()+"-"+year.toString();
}
// create new moment obj
curDayofMonth = moment(curDayofMonthString,"DD-MM-YYYY");
daysInMonth--;
}
// return array with information on the month
return daysArr;
}
You can then access the days like this
Array.from(MomentObjDaysInMonthArray).forEach(obj =>{
console.log(obj.day());
});
Where:
0: Sunday
1: Monday
2: Tuesday
3: Wednesday
4: Thursday
5: Friday
6: Saturday
I am helping a friend in his mini project and at this moment we are standing in the following situation: For example a doctor tells his patient that as of TODAY you have X numbers of consultations, every Wednesday and Friday, how to get the dates of these consultations, assuming that TODAY, it can be any day of the week ???
Thanks
I'm not sure if that is what you want but you can achieve that, for example, like this.
//get current date
var date = new Date ()
//array with week-day names
var week_days = [
'Sunday',
'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Saturday'
];
//your initial variables
var consultations = ['Wednesday', 'Friday'];
var X = 5;
//loop through X + 1 weeks to find dates and count results
var count = 0
for (var i = 0; i < (X + 1) * 7; i++) {
//get name of date-day
var week_day = week_days[date.getDay ()];
//check if wanted
if (consultations.indexOf (week_day) != -1) {
//construct date and output
var day = date.getDate ();
var month = date.getMonth ();
var year = date.getFullYear ();
document.write (day + '.' + month + '.' + year);
document.write ('<br/>');
//increment count
count++;
//stop if count == X
if (count == X)
break;
}
//increment date
date.setDate (date.getDate () + 1);
}
i'm programming a calendar and i need to know what the first day of each month is. Like, This month, hte first day was on a sunday. How would i go about to figure that out for all months of the year? Or any month for that matter.
Thanks in advance!
edit: the day can be returned as an integer.
Where options for toLocaleString are supported, you can use it to get the day name in the browser default language:
function getDayName(date) {
return date.toLocaleString(undefined, {weekday:'long'});
}
function getMonthName(date) {
return date.toLocaleString(undefined, {month:'long'});
}
// Create a date
var d = new Date();
// Set to first of month
d.setDate(1);
// Create string
console.log(`The first of ${getMonthName(d)} was a ${getDayName(d)}.`);
Of course mixing English with some other language may not be appropriate…
You could create a method that returns the day name
function(year, month){
var date = new Date(year, month, 1);
var days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
return days[date.getDay()];
}
JavaScript already provides this out of the box be using getDay.
new Date().getDay()
This will return 0-6. Depends on what weekday it is.
If you need it as a readable string you may want to do something like this:
var weekdays = [
'Sunday',
'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Saturday'
];
console.log(weekdays[new Date().getDay()]);
Knowing this you can go furter:
const year = new Date().getFullYear();
const weekdays = [
'Sunday',
'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Saturday'
];
[0,1,2,3,4,5,6,7,8,9,10,11].forEach(x => {
const weekday = new Date(year, x, 1).getDay();
console.log(weekdays[weekday]);
});
See: MDN
I would highly recommend using MomentJS library if you are not already using it. Using moment, you can get the day of 1st of any month using this single statement:
moment("2017-11-01").startOf('month').format("dddd")
If you cannot use moment for some reason, then you could just create a function that takes in month and year and returns back the day of 1st of that month. You need to use Date.prototype.getDay() for this, which returns a value from 0 to 6, where 0 means Sunday.
$("#get-day").on("click", function(e){
var year = $("#year").val();
var month = $("#month").val();
alert( getDay(year, month) );
});//#get-day click()
function getDay(year, month){
var days = ["Sun", "Mon", "Tues", "Wed", "Thurs", "Fri", "Sat"];
var dayIndex = new Date(year + "-" + month + "-01").getDay();
return days[ dayIndex ];
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="year" value="2017" />
<input type="text" id="month" value="10" />
<button id="get-day">Get Day on 1st</button>
The .getDay() method returns an integer, the day of the week for the specified date according to local time, where Sunday = 0 and Saturday = 6. Here's an example using this:
dateFunction = function(myDate){
var days =
["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]
var dayInt = new Date(myDate).getDay()
return days[dayInt]
}
var FirstDayOfOctober = dateFunction("2017-10-01");
This question already has an answer here:
Finding the second and fourth Tuesday of the month with Javascript
(1 answer)
Closed 9 years ago.
After several searches, I haven't been able to find what I'm looking for. Im using jquery datepicker to return a date string that looks like Day, Month Date, YYYY, and I am looking for a library or some method that will take that and turn it into
the second Tuesday of the month, or the fourth Thursday of the month. So far it seems like jquery's prettyDate and EasyDate dont have the functionality I'm looking for, and I would love to avoid doing this by hand!
Thanks,
Alex
You don't need a date library - just take the date, divide by 7 and round up.
//format: Day, Month Date, YYYY
var ordinals = ["", "first", "second", "third", "fourth", "fifth"];
var date = "Friday, May 10, 2013";
var tokens = date.split(/[ ,]/);
// tokens = ["Friday", "", "May", "10", "", "2013"];
console.log( "The " + ordinals[Math.ceil(tokens[3]/7)] + " " + tokens[0] + " of the month");
function nthDay(D){
var nth= ['First', 'Second', 'Third', 'Fourth', 'Fifth'],
dayNames= ['Sunday', 'Monday', 'Tuesday', 'Wednesday',
'Thursday', 'Friday', 'Saturday'],
monthNames= ['January', 'February', 'March', 'April', 'May', 'June',
'July', 'August', 'September', 'October', 'November', 'December'];
return nth[Math.floor(D.getDate()/7)]+' '+
dayNames[D.getDay()]+' of '+monthNames[D.getMonth()];
}
nthDay(new Date(2013, 4, 10))
/* returned value:
Second Friday of May
*/
Here's a script I used back in the day, if momentjs doesn't work out for you (although I really think momentjs is a better solution).
/*
Parameters:
index: n'th occurrence of the specified day
day: daynumber - javascript way where sunday is 0 and is saturday is 6
month: javascript way which is 0-11 [optional - defaults to current]
year: Full year - four digits [optional - defaults to current]
*/
function getNthDayOfMonth(index,day,month,year){
// Create date object
var date = new Date();
// Set to first day of month
date.setDate(1);
// If supplied - set the month
if(month!==''&&month!==undefined){
// Set month
date.setMonth(month);
}else{
month = date.getMonth();
}
// If supplied - set the year
if(year!==''&&year!==undefined){
// Set year
date.setFullYear(year);
}else{
year = date.getFullYear();
}
// Find daynumber
firstDay = date.getDay();
// Find first friday.
while(date.getDay()!=day){
date.setDate(date.getDate()+1) ;
}
switch(index){
case 2:
date.setDate(date.getDate()+7);
break;
case 3:
date.setDate(date.getDate()+14);
break;
case 4:
date.setDate(date.getDate()+21);
break;
case 5:
date.setDate(date.getDate()+28);
if(date.getMonth()!==month){
date = null;
}
break;
}
return date;
}
In Date.js you have some helpful functions like moveToFirstDayOfMonth and getWeek.
Then you can get the week of the first day of the month and subtract those two to get the week of the month.
Here is a simple example using Date.js and going off of today but you can pass in your own date. I am not too familiar with other Date libraries but I think you can recreate something like this below.
function dayOfWeekToday(){
//Get the total weeks on the year from this day
var totalWeek = Date.today().getWeek();
//Get the first day of this month
var firstOfMonth = Date.today().moveToFirstDayOfMonth();
//Get the total weeks form the first day of the month
var weeksAtStartOfMonth = firstOfMonth.getWeek();
//Get the week of the month
var week = totalWeek - weeksAtStartOfMonth;
//Get the day(0-6) of today and the first day
var today = Date.today().getDay();
var firstDay = firstOfMonth.getDay();
//If today is before the firstDay then the week will be off by one
if(today < firstDay){
week--;
}
//Get the day form of the string
var day = Date.today().toString("dddd");
//Translate from a number to a string
var str = "first";
if(week === 1){
str = "second";
}else if(week === 2){
str = "third";
}else if(week === 3){
str = "fourth";
}else if (week === 4){
str = "fifth";
}
//Result
return "The "+str+" "+day+" of the month";
}
I wrote some simple logic that just works backwards from the value of the date:
function calculateNthDate(startDateDay, startDateValue){
var day = startDateDay;
var date = startDateValue;
var i = 0;
while(date >= 0){
if (date > 0 ){
i++;
}
date = date - 7;
}
var string = "The "+i+'th '+day+" of the month.";
}
edit: the th will have to be customized for nd, st, and rd .