JS dates, first day of the month - javascript

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");

Related

Javascript: array ask the current day from the week

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)

Create days array from Today till seven days ago with date-fns

In my React component, I have to render a list of days: from Today - seven days ago.
Like: Today / Yesterday / Monday / Tuesday / Wednesday / Thursday / Friday.
I am using date-fns.
const generateDays = () => {
const date: Date = new Date();
const a = subDays(date, 4);
const formatted = format(a, 'eeee', { locale: nl });
return formatted;
};
How do I accomplish this in an smooth way?
What I tried:
const today = new Date();
const sevenDaysAgo = subDays(today, 6);
const sevenDays = eachDayOfInterval({ start: sevenDaysAgo, end: today });
sevenDays.forEach((day) => {
console.log(format(day, 'eeee', { locale: nl }));
});
This returns:
['Wednesday', 'Tuesday', 'Monday', 'Sunday', 'Saturday', 'Friday', 'Thursday']
To get the week day from the dayOffset (replace 'en-us' with your country's code if you're not American) you can do the following.
const offset_date = new Date();
offset_date.setDate(offset_date.getDate() + dayOffset);
const week_day = offset_date.toLocaleString('en-us', {weekday: 'long'});
You can use the formatRelative function from the date-fns library, it formats the dates in words from a given date.
Here is a code sandbox link that might be helpful.

Get the Dayname of string date js

Hi I am new to javascript I am trying to get the name of my date string
formatted dd/MM/yyyy
ex:
23/02/2019
expected output: Saturday
my code giving Nan. I will really appreciate any advice or help. Thank you
var ot="23/02/2019";
var days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
var d = new Date(ot);
var dayName = days[d.getDay()];
console.log(dayName);
Your new Date(ot) might be failing because of timezone issues. For safer side, you can break down your date string and pass it to new Date() as year, month, date.
JS months are index based so -1 from month in string
var ot="23/02/2019";
var days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
var otArr = ot.split('/')
var d = new Date(otArr[2], otArr[1] - 1, otArr[0]);
var dayName = days[d.getDay()];
console.log(dayName);
Format to get a new date object with year , month and date is new Date(year,month,date);
To extract them seperately from the string date formatted (date/month/year) we need to split them by slash and provide the required parameters to the function as shown below.
var ot="23/02/2019";
var days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
var splits = ot.split('/');
// var d = new Date(ot.split('/')[2],ot.split('/')[1] -1 ,ot.split('/')[0]);
var d = new Date(splits[2],splits[1] -1 ,splits[0]);
var dayName = days[d.getDay()];
console.log(dayName);

How to get the Day names and Number of days based on month and year

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

Print weekdays and check if a date exists for this weekday

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.

Categories