Get name of the month [duplicate] - javascript

It's possible to do this to get the localized full month name using native javascript.
var objDate = new Date("10/11/2009"),
locale = "en-us",
month = objDate.toLocaleString(locale, { month: "long" });
But this only gets the month number for a given date. I'd simply like to get the month name corresponding to a month number. For example, if I do getMonth(2) it would return February. How can I implement getMonth using native javascript(no libraries like moment)?

You are already close:
var getMonth = function(idx) {
var objDate = new Date();
objDate.setDate(1);
objDate.setMonth(idx-1);
var locale = "en-us",
month = objDate.toLocaleString(locale, { month: "long" });
return month;
}
console.log(getMonth(1));
console.log(getMonth(12));

To get all the months of a year and days of the week, loop over a set of dates and use toLocaleString with appropriate options to get the required values:
function getLocalDayNames() {
let d = new Date(2000,0,3); // Monday
let days = [];
for (let i=0; i<7; i++) {
days.push(d.toLocaleString('default',{weekday:'long'}));
d.setDate(d.getDate() + 1);
}
return days;
}
console.log(getLocalDayNames());
function getLocalMonthNames() {
let d = new Date(2000,0); // January
let months = [];
for (let i=0; i<12; i++) {
months.push(d.toLocaleString('default',{month:'long'}));
d.setMonth(i + 1);
}
return months;
}
console.log(getLocalMonthNames());
The language default means toLocaleString uses the default language of the implementation that the code is running in.

Related

How do I get an array of all days in the week given the current date in javascript?

I have the weekday value (0-6 for Sun-Sat)...how do I get an array of days (starting on Sunday for the given week?
Here is what I'm trying to do:
A user clicks a day (ie: May 10) and it generates an array of the dates for the current week:
function selectWeek(date) {
selectedWeek = [];
let d = new Date(date.key);
console.log(d);
console.log(date.weekday, 'weekday');
console.log(date);
for (let i = 0; i < date.weekday; i++) {
console.log(i, 'pre');
let currD = d.setDate(d.getDate() - i).toString();
console.log(currD);
selectedWeek.push(currD);
}
for (let i = date.weekday; i < 7; i++) {
console.log(i, 'post');
selectedWeek.push(d.setDate(d.getDate() + i).toString());
}
console.log(selectedWeek);
}
I need Sunday through Saturday date objects.
I am not using a date library so prefer vanilla javascript solutions.
Create an array with 7 elements, subtract the weekday and add the index as day:
function selectWeek(date) {
return Array(7).fill(new Date(date)).map((el, idx) =>
new Date(el.setDate(el.getDate() - el.getDay() + idx)))
}
const date = new Date();
console.log(selectWeek(date));
I'm using
fill(new Date(date))
to create a copy and not modify the argument.
You can get the days of a month with the same concept:
function selectMonth(date) {
return Array(31).fill(new Date(date)).map((el, idx) =>
new Date(el.setDate(1 + idx))).filter(el => el.getMonth() === date.getMonth());
}
const date = new Date();
console.log(selectMonth(date));
here's how I would solve this one:
function selectWeek(date) {
let selectWeek = [];
for (let i=0; i<7; i++) {
let weekday = new Date(date) // clone the selected date, so we don't mutate it accidentally.
let selectedWeekdayIndex = date.getDay() // i.e. 5 for friday
let selectedDay = date.getDate() // 1-31, depending on the date
weekday.setDate(selectedDay - selectedWeekdayIndex + i)
selectWeek = [...selectWeek, weekday]
}
return selectWeek;
}
Let's take today's date as an example: 18.02.22. Friday.
We do 6 iterations. On first one we get the selectedWeekdayIndex, which is 5 for friday. We clone the date and re-set it's day (18) reducing it by this number: 18-5 = 13. This is the day for Sunday. Then we go on incrementing days by one to fill the rest of the week.
Of course it can be optimised and written much shorter, but I tried to show and explain the logic.
The .getDay() gives you the day of the week.
function selectWeek(date) {
const selectWeek = [];
let temp = date;
while (temp.getDay() > 0) temp.setDate(temp.getDate() - 1); // find Sunday
// get the rest of the week in the only do while loop ever created
do {
selectWeek.push(new Date(temp));
temp.setDate(temp.getDate() + 1);
} while (temp.getDay() !== 0);
return selectWeek;
/* for display purposes only */
// const dates = selectWeek.map((date) => date.toString());
// console.log(dates);
}
selectWeek(new Date());
selectWeek(new Date("2020-01-01"));
selectWeek(new Date("december 25, 1990"));
Did you check Date prototypes before?
I think Date.prototype.getDay() can do what you want:
function selectWeekDays(date) {
var i,
d = new Date(date),
a = [];
// console.log(d.getDay()); // Number of the day
d.setDate(d.getDate() - d.getDay() - 1); // Set date one day before first day of week
for (i=0; i<7; i++) {
d.setDate(d.getDate() + 1); // Add one day
a.push(d.valueOf());
}
return a;
}
var result = selectWeekDays('2022-01-01') // Satureday = 6
console.log(result);
result.forEach(e => console.log(new Date(e).toString()));

Javascript how to get full two year from current month?

I have question about getting full two years from the current date. So what i did id get the current month using the new date function and used the for loop to print each of the month. But, i cant really get it to work.... I will post the code that i did below. I would be really appreciate it if anyone can tell me the logic or better way of doing it.
For example: if today current date is august it store into an array from 8 / 2020 9/ 2020 ..... 12/ 2020, 1/2021 and goes to another year to 8/2022.
var d = new Date();
var year = d.getFullYear();
var dateStr;
var currentYear;
var storeMonthYear = [];
for(var i = 1; i <= 24; i++){
dateStr = d.getMonth() + i
currentYear = year;
if(dateStr > "12"){
dateStr = dateStr - 12
// currentYear = year;
// if(currentYear){
// }
storeMonthYear[i] = dateStr + "/" + (currentYear + 1);
}
else if(dateStr > "24"){
storeMonthYear[i] = dateStr + "/" + (currentYear + 1);
}
else{
storeMonthYear[i] = dateStr + "/" + currentYear;
}
storeMonthYear[i] = d.getMonth() + i
}
export const settlementPeriod = [
{
MonthYearFirstRow1: storeMonthYear[1],
MonthYearFirstRow2: storeMonthYear[2],
MonthYearFirstRow3: storeMonthYear[3],
MonthYearFirstRow4: storeMonthYear[4],
MonthYearFirstRow5: storeMonthYear[5],
MonthYearFirstRow6: storeMonthYear[6],
MonthYearFirstRow7: storeMonthYear[7],
MonthYearFirstRow8: storeMonthYear[8],
MonthYearFirstRow9: storeMonthYear[9],
MonthYearFirstRow10: storeMonthYear[10],
MonthYearFirstRow11: storeMonthYear[11],
MonthYearFirstRow12: storeMonthYear[12],
MonthYearSecondRow13: storeMonthYear[13],
MonthYearSecondRow14: storeMonthYear[14],
MonthYearSecondRow15: storeMonthYear[15],
MonthYearSecondRow16: storeMonthYear[16],
MonthYearSecondRow17: storeMonthYear[17],
MonthYearSecondRow18: storeMonthYear[18],
MonthYearSecondRow19: storeMonthYear[19],
MonthYearSecondRow20: storeMonthYear[20],
MonthYearSecondRow21: storeMonthYear[21],
MonthYearSecondRow22: storeMonthYear[22],
MonthYearSecondRow23: storeMonthYear[23],
MonthYearSecondRow24: storeMonthYear[24]
},
];
Create the date from today, get the month and year. Iterate from 0 to 24 for now till in 24 months. If month is 12 than set month to 0 and increment the year. Push the new datestring. Increment the month for the next step.
Note: Beacsue JS counts months form 0-11 you had to add for the datestring 1 for the month and make the change of year at 12 and not 13.
let date = new Date();
let year = date.getFullYear();
let month = date.getMonth();
let res=[];
for (let i=0; i<=24; i++) {
if (month===12) {
month = 0;
year++;
}
res.push(month+1 + '/' + year);
month++;
}
console.log(res);
Here you go, you get an array of strings like "8/2020","9/2020" etc from starting month to the last month including both( in total 25 months).
If you don't want to include last month just delete +1 from for loop condition.
let currentDate = new Date();
let settlementPeriod = [];
let numberOfMonths = 24;
for(let i=0;i<numberOfMonths+1;i++){
settlementPeriod.push(currentDate.getMonth()+1+"/"+currentDate.getFullYear()); //We add current date objects attributes to the array
currentDate = new Date(currentDate.setMonth(currentDate.getMonth()+1)); //Every time we add one month to it
}
console.log(settlementPeriod);
There are a couple of things that stick out in your code sample:
You're comparing strings and numbers (e.g. dateStr > "12"). This will lead to some weird bugs and is one of JS's most easily misused "features". Avoid it where possible.
You increment the year when you reach 12 months from now, rather than when you reach the next January
You're overwriting your strings with this line storeMonthYear[i] = d.getMonth() + i so your array is a bunch of numbers rather than date strings like you expect
Here's a code sample that I think does what you're expecting:
function next24Months() {
const today = new Date()
let year = today.getFullYear()
let monthIndex = today.getMonth()
let dates = []
while (dates.length < 24) {
dates.push(`${monthIndex + 1}/${year}`)
// increment the month, and if we're past December,
// we need to set the year forward and the month back
// to January
if (++monthIndex > 11) {
monthIndex = 0
year++
}
}
return dates
}
In general, when you're dealing with dates, you're probably better off using a library like Moment.js - dates/times are one of the most difficult programming concepts.
While #Ognjen 's answer is correct it's also a bit waseful if your date never escapes its function.
You don't need a new date every time:
function getPeriods(firstMonth, numPers){
var d = new Date(firstMonth.getTime()); // clone the start to leave firstMonth alone
d.setDate(1); // fix after #RobG
var pers = [];
var m;
for(var i = 0; i< numPers; i++){
m = d.getMonth();
pers.push(`${m+ 1}/${d.getFullYear()}`)
d.setMonth(m + 1); // JS dates automatically roll over. You can do this with d.setDate() as well and when you assign 28, 29, 31 or 32 the month and year roll over automatically
}
return pers;
}

Converting C# date-time function to Javascript

I have an application in which I use a couple of date/time manipulation function to populate a couple of calendars. Basically, a user selects a month/year from a dropdown (say, March 2019) and I populate the calendars with 03/01/2019 and 03/31/2019.
I wanted to do this client side so tried to convert those function to javascript and I am getting strange results and can't see what I am doing wrong.
This is the original C# functions I defined and used:
public static DateTime FirstDayOfMonth(this DateTime dt)
{
return new DateTime(dt.Year, dt.Month, 1);
}
public static DateTime LastDayOfMonth(this DateTime dt)
{
DateTime dtFirstDayOfMonth = new DateTime(dt.Year, dt.Month, 1);
DateTime dtLastDayOfMonth = dtFirstDayOfMonth.AddMonths(1).AddDays(-1);
return dtLastDayOfMonth;
}
I called these like below:
DateTime dtSelected = DateTime.Today.AddMonths(int.Parse(ddlMonth.SelectedValue)).AddYears(-1);
dtStartDate = Utils.FirstDayOfMonth(dtSelected);
dtEndDate = Utils.LastDayOfMonth(dtSelected);
The dropdown list is populated like:
for (int i = 12; i >= 1; i--)
{
string s = DateTime.Now.AddYears(-1).AddMonths(i).ToString("Y");
ListItem li = new ListItem(s, i.ToString());
ddlMonth.Items.Add(li);
}
The dropdown entries would look like:
May, 2019 -- value of 12
April, 2019 -- value of 11
....
July, 2018 -- value of 2
June, 2018 -- value of 1
This is my attempt at translating to javacript:
function firstDayOfMonth(dt) {debugger
var year = dt.getFullYear();
var month = dt.getMonth();
var day = dt.getDate();
return new Date(year, month, 1);
}
function lastDayOfMonth(dt) {debugger
var year = dt.getFullYear();
var month = dt.getMonth();
var day = dt.getDate();
var firstDayOfMonth = new Date(year, month, 1);
var lastDayOfMonth = firstDayOfMonth.AddMonths(1).AddDays(-1); --> shows error when called; Object doesn't support property or method 'AddMonths'
return lastDayOfMonth;
}
$(document).on('change', '#ddlMonth', function () {debugger
var monthID = this.value;
var ddlMonth = $('#ddlMonth');
var today = new Date();
var startDate = new Date();
var endDate = new Date();
var dtSelected = new Date();
if (ddlMonth.val() == "")
{
....
}
else
{debugger
dtSelected.setMonth(dtSelected.getMonth() + ddlMonth.val() + 1); -- this becomes "Wed Oct 12, 2360" if I select "March, 2019" from dropdown!
dtSelected.setFullYear(dtSelected.getFullYear() - 1);
dtStartDate = firstDayOfMonth(dtSelected);
dtEndDate = lastDayOfMonth(dtSelected);
}
you have some problem in your code, this for example:
dtSelected.setMonth(dtSelected.getMonth() + ddlMonth.val() + 1); -- this becomes August of 2036!
you take today's month which is the 5 then add to itsome value from your slect and add 1 more and this is a lot of monthes to add.
I think you need to changesome things and do this like this:
change the select values to be the date of the first day of each month and not just number:
for (int i = 12; i >= 1; i--)
{
DateTime date = DateTime.Now.AddYears(-1).AddMonths(i);
ListItem li = new ListItem(date.ToString("Y"), date.ToString("yyyy-MM-01"));
ddlMonth.Items.Add(li);
}
in this format you can use it on js with no problem.
now for your js function:
function lastDayOfMonth(dt) {debugger
var year = dt.getFullYear();
var month = dt.getMonth();
var day = dt.getDate();
var lastDayOfMonth = new Date(year, month, 1);
lastDayOfMonth.setMonth(lastDayOfMonth.getMonth() + 1);
lastDayOfMonth.setDate(lastDayOfMonth.getDate() - 1);
return lastDayOfMonth;
}
$(document).on('change', '#ddlMonth', function () {debugger
var ddlMonth = $('#ddlMonth');
dtStartDate = new Date(ddlMonth.val());
dtEndDate = lastDayOfMonth(dtStartDate);
}

How to exclude weekends in date object in Javascript

I'm facing issue with excluding weekend dates in JavaScript.For my business requirement I want to exclude 3 days from date object Friday, Saturday and Sunday in every week.What I need here is the values of Friday should display as Monday, Saturday as Tuesday and Sunday as Wednesday. I'm able to do this.
The issue that I'm facing here is when we run the above example the a[0] value should be 21-SEP-2017 but I'm getting 20-SEP-2017 and remaining array values should not change. So please do help me out in resolving this issue
var a = ["21-SEP-2017", "22-SEP-2017", "23-SEP-2017", "24-SEP-2017", "25-SEP-2017"];
for (i = 0; i < a.length; i++) {
var startDate = a[i];
startDate = new Date(startDate.replace(/-/g, "/"));
var endDate = "",
noOfDaysToAdd = 1;
var count = 0;
endDate = new Date(startDate.setDate(startDate.getDate()));
if (startDate.getDay() != 0 && startDate.getDay() != 5 && startDate.getDay() != 6) {
endDate = new Date(startDate.setDate(startDate.getDate() + i - 1));
} else {
startDate.setDate(startDate.getDate() + 3)
endDate = new Date(startDate.setDate(startDate.getDate()));
}
console.log(endDate); //You can format this date as per your requirement
}
Your code seems not finished: the variables noOfDaysToAdd and count are never used, and if they were, they would be reset in every iteration of the loop, which cannot be the purpose.
That your output shows 20 September is because you did not output a stringified version of the date, but the date object itself, and then console.log will display the date as a UTC date (notice the time part matches the timezone difference). Instead use .toString() or another way to turn the date to a localised string.
Here is how you could do it:
function toDate(s) {
return new Date(s.replace(/-/g, '/'));
}
function toStr(dt) {
var months = ["JAN","FEB","MAR","APR","MAY","JUN",
"JUL","AUG","SEP","OCT","NOV","DEC"];
return [('0'+dt.getDate()).substr(-2), months[dt.getMonth()], dt.getFullYear()]
.join('-');
}
var a = ["21-SEP-2017", "22-SEP-2017", "23-SEP-2017", "24-SEP-2017", "25-SEP-2017"],
add = 0;
var result = a.map(toDate).map(dt => {
dt.setDate(dt.getDate()+add);
var move = [0, 6, 5].indexOf(dt.getDay()) + 1;
if (move) {
add += move;
dt.setDate(dt.getDate()+move);
}
return dt;
}).map(toStr);
console.log(result);

Javascript OO Function

I need something obvious pointing out to me in regard to JS functions.
The following code works, but I want to call upon it anywhere:
var pattern = /(\d{2})\-(\d{2})\-(\d{4})/;
var date = entry.date.split(' ');
var date = date[0];
var date = new Date(date.replace(pattern,'$3-$2-$1'));
var year = date.getYear();
var month = date.getMonth();
var day = date.getDay();
What would be the best practice to place this in a global function so I can just do adjustDate(string). Double points (Sadly, not in my power) to explain how I would then also have access to all the objects such as year, month, day.
Thanks in advance!
Can't you just declare the function?
function adjustDate(entry) {
var date = entry.date.split(' ');
date = date[0];
date = new Date(date.replace(/(\d{2})\-(\d{2})\-(\d{4})/, '$3-$2-$1'));
return {
year: date.getYear(),
month: date.getMonth(),
day: date.getDay()
};
}
I would just return a date without abstracting its existing methods
function AdjustedDate(dateString)
{
return new Date(dateString.split(' ')[0].replace(/(\d{2})\-(\d{2})\-(\d{4})/, '$3-$2-$1'));
}
var ad = AdjustedDate(entry.date);
alert(ad);
alert(ad.getDay());
Pass the entry into the function and then pass an object containing the information you want out. Then just access it like you would an ordinary JS object.
function adjustDate(entry) {
var pattern = /(\d{2})\-(\d{2})\-(\d{4})/;
var date = entry.date.split(' ');
var date = date[0];
var date = new Date(date.replace(pattern,'$3-$2-$1'));
var year = date.getYear();
var month = date.getMonth();
var day = date.getDay();
return { day: day, month: month, year: year }
}
var dateObject = adjustDate(/*entry*/)
dateObject.day // day
dateObject.month // month

Categories