How to find the next and previous months with JavaScript? - javascript

My jQuery function takes in the current month. I would like to display the next and previous months depending on the buttons clicked.
My question is, is there a default Date() function I can call to know the next and previous months of a current month ?
$(document).ready(function () {
var current_date = $('#cal-current-month').html();
//current_date will have September 2013
$('#previous-month').onclick(function(){
// Do something to get the previous month
});
$('#next-month').onclick(function(){
// Do something to get the previous month
});
});
I can write some code and get the next and previous months, but I was wondering if there is any already defined functions for this purpose?
SOLVED
var current_date = $('.now').html();
var now = new Date(current_date);
var months = new Array( "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
$('#previous-month').click(function(){
var past = now.setMonth(now.getMonth() -1);
$('.now').html(months[now.getMonth()]+' '+now.getFullYear());
});
$('#next-month').click(function(){
var future = now.setMonth(now.getMonth() +1);
$('.now').html(months[now.getMonth()]+' '+now.getFullYear());
});

If you just want to get the first day of the next month, you could do something like:
var now = new Date();
var future = now.setMonth(now.getMonth() + 1, 1);
var past = now.setMonth(now.getMonth() - 1, 1);
This will prevent the "next" month from skipping a month (e.g. adding a month to January 31, 2014 will result in March 3rd, 2014 if you omit the second parameter).
As an aside, using date.js* you could do the following:
var today = Date.today();
var past = Date.today().add(-1).months();
var future = Date.today().add(1).months();
In this example I am using today's date, but it works for any date.
*date.js has been abandoned. If you decide to use a library, you should probably use moment.js as RGraham suggests.

Related

How to get month name for a given year and week in Javascript

I have 2 form fields in HTML namely Year and Week.
Once the user selects a Year and a week from the dropdowns, I want to display the month Name for the selected year and week.
Can anyone help me to get month name based on year and iso week numbers.
For example: If I selected year as 2022 and week no as 16, then the expected output is April as a month name.
This shoud be a function that returns the month name for a given year and week.
Below is my sampke code.
getMonthName() {
const year = 2022;
const week = 16;
console.log(month);
}
The following will display the month name (short form) for the given ISO week number and year.
function getMonthName(week, year) {
let d =new Date(year,0,1+(week-1)*7);
d.getUTCDay()<5?d.setUTCDate(d.getUTCDate()-d.getUTCDay()+1):d.setUTCDate(d.getUTCDate()+8-d.getUTCDay());
return (""+d).split(" ")[1];
}
console.log(getMonthName(1,2022));
console.log(getMonthName(11,2022));
console.log(getMonthName(16,2022));
Example: https://codesandbox.io/s/damp-wood-nynj7f?file=/src/app/app.component.ts
Create mapper for your months:
4 weeks = 1 month, then get input value of week covert to number and divide 4. (Example: 16 / 4 === 4)
The result is a key of your mapper: months[divided result]
The best is a using Date libraries such as: dayjs, date-fns, moment, luxon or other.
const months = {
1: "January",
2: "February"
}
changeWeekHandler(e) {
const week = parseInt(e.target.value)
const month = Math.ceil(week / 4) // for round number to the upper (example: Math.ceil(0.25) -> 1)
this[your input field] = months[month]
}
Really interesting form. I came up with a solution like this;
I do not suggest you divide by 4 weeks per month because not all months have 4 weeks.
But from your input, you always can know the day of year from a number of weeks
numberOfWeek * 7 = numberOfDay
create a method :
const dateFromDay = (year, day = 1) => {
const date = new Date(year, 0);
return new Date(date.setDate(day));
}
// call the method with your inputs
const myDate = edateFromDay(2022,16*7);
// here you will have the full date
// if you want just the month then
myDate.getMonth();
For exact your need :
//Declare months
const monthNames = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
];
// Declare method for receiving your month name
const dateFromWeek = (year, week = 1) => {
const date = new Date(year, 0);
return monthNames[new Date(date.setDate(week*7)).getMonth()];
}
//When you use
dateFromWekk(2020,3); //just write year and week, you will get the name of month

Display all 12 months serially but starting from the current month

I am working on a requirement where I have 12 ion slides and the names of the slides are month names starting from the current month. For ex: If the current month is June, then the name of the first slide should start from June 2020 and go on till May 2021. Well I tried it but not able to achieve. Even if I handle the month, then I am not able to dynamically change the year after December. Here is my code:
my html file
<ion-toolbar class="toolbars" #ionDragFooter>
<ion-title class="ion-text-center">{{currValue}}</ion-title>
</ion-toolbar>
My .ts file
ngOnInit() {
swipeNext()
}
var monthNames = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"];
var d = new Date();
if(index == 1){
var curMn=monthNames[d.getMonth()]+ d.getFullYear();
console.log(curMn)
this.currValue=curMn;
}
else if(index == 2){
var curMn=monthNames[d.getMonth()+1]+ d.getFullYear();
this.currValue=curMn;
}
else if(index == 3){
var curMn=monthNames[d.getMonth()+2]+ d.getFullYear();
this.currValue=curMn;
}
and so on for all other month. I need to completely automate the month and year starting from the current month. May I know where I went wrong?
You can create a date, then increment the month by 1 eleven times to get 12 months of dates. The month name can be found using toLocaleString with appropriate options.
You need to be careful when incrementing months, e.g.
let d = new Date(2020,0,31); // 31 Jan 2020
d.setMonth(d.getMonth() + 1) // 31 Feb 2020 -> 2 Mar 2020
d.toDateString(); // Mon Mar 02 2020
So best to set the date to the 1st of the month initially:
// Optionally provide a date for the starting month
function getMonthNames(date = new Date()) {
// Copy input date so don't modify it
let d = new Date(+date);
// Set to 1st of month
d.setDate(1);
let result = [];
// Get 12 month names, starting with current month
for (let i=0; i<12; i++) {
result.push(d.toLocaleString('default',{month:'long'}));
d.setMonth(d.getMonth() + 1);
}
return result;
}
console.log(getMonthNames());
To properly change the date you have to increase the date by the amount of months in the date object (in your case d):
var d = new Date();
//REM: This will print out the next month, yet d still is unchanged
console.log(d.getMonth()+1);
console.log(d);
console.log('Month did not increase: ', d.getMonth());
//REM: You have to increase your date by one month in the date object
d.setMonth(d.getMonth() + 1);
console.log(d);
console.log('Month did increase: ', d.getMonth());
//REM: By which it will change the year for you, once it is time for it.
d.setMonth(d.getMonth() + 11); //REM: +1 from before
console.log(d);
console.log('Year did increase: ', d.getFullYear());
In your case that would be:
var monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var d = new Date();
d.setDate(1); //REM: To prevent month skipping.
for(var i=0; i<12; i++){
d.setMonth(d.getMonth() + 1);
console.log(monthNames[d.getMonth()], d.getFullYear())
};
Some further reading on the issue
This is what I came up with:
const monthNames = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"];
const today = new Date();
//gives you year
const year = today.getFullYear();
//gives you month as number/index;
const month = today.getMonth();
//stores sequenced month names
const sequencedNames = [];
//creates June 2020 through December 2020
for(let i = month; i < monthNames.length; i++) {
let monthName = monthNames[i];
sequencedNames.push(monthName + " " + year)
}
//creates January 2021 through May 2021
for(let i = 0; i < month; i++) {
let monthName = monthNames[i];
sequencedNames.push(monthName + " " + (year + 1))
}
console.log(sequencedNames)
Essentially 2 for loops, the first iterating from the current month to the end of the year, and then the second from the start of the year to the current month -- though adding 1 year.

How to get previous 6 months date from current date in javascript

I am trying get last six months date from current date .
var d = new Date();
var months = ["January","February","March","April","May","June","July","August","September","October","November","December"];
alert(months[d.getMonth()-6]);
but i am getting udefined
I always recommend using date libraries to assist in these types of calculations. One of the most popular with a ton of support and examples is moment.js (https://momentjs.com/)
To get six months ago from the current date using moment is:
moment().subtract(6, 'months')
and then to print the month name would be:
moment().subtract(6, 'months').format('MMMM')
You have to write your code like below-
var d = new Date();
var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
d.setMonth(d.getMonth() - 6);
console.log(months[d.getMonth()]);
We need to get Month from date object the set to back (with - 6) then get it back.
var d = new Date();
var months = ["January","February","March","April","May","June","July","August","September","October","November","December"];
var monthName = months[new Date(d.setMonth(d.getMonth() - 6)).getMonth()];
console.log(monthName)

Parse and return components of a date using Javascript

I have a series of dates formatted similar to 2014-12-31 (year, month, day) loading into a webpage.
I'd like to use Javascript to reformat the date to appear as December 31, 2014 (month, day, year).
Is it possible to do this without splitting the string and reformatting; in other words, is it possible to only use Javascripts date() function?
For example, if I try:
d = new Date.parse('2014-12-31')
Is there a way to return only the year, month or day?
I tried d.getYear(), but that threw a "function not found" error.
Can you use momentjs.com? it's far more powerful than the default.
var yourInput = "2014-12-31";
var moment = require("moment");
var d = moment(yourInput);
var iYear = d.year();
var iMonth = d.month();
var iDay = d.day();
It is possible, but what I am showing is not very pretty, so I agree that using the well-established moment.js is a better idea. If you must not use libraries...
You have to be careful if the user is behind GMT, because creating a new Date (without a time in hours) will then be set to the previous day. getTimezoneOffset() is used to correct the desired date to midnight.
Also, you have to define an array of months to be displayed. By default, getting a month returns an integer from 0 to 11. (Jan = 0)
function myDateFormat(ymd) {
var rawDate = new Date(ymd);
var midnight = new Date(rawDate.getTime() +
rawDate.getTimezoneOffset() * 60 * 1000);
var months = ["January", "February", "March", "April",
"May", "June", "July", "August",
"September", "October", "November", "December"]
return months[midnight.getMonth()] + " " +
midnight.getDate() + ", " + midnight.getFullYear();
}
// test function
function display(x) {
document.getElementById("result").innerHTML += x + "\n";
}
display("2015-02-15 is " + myDateFormat("2015-02-15"));
display("2014-12-31 is " + myDateFormat("2014-12-31"));
display("2015-10-10 is " + myDateFormat("2015-10-10"));
<pre id="result"></pre>
You should just use var d = new Date('2014-12-31');
Date.parse returns the number of milliseconds since the Unix epoch, not a Date object.

JavaScript: Print previous 12 months -- "March" prints twice?

I'm trying to write a script that prints the names of the previous 12 months. Since this month is January, it should print: December
November
October
September
August
July
June
May
April
March
February
January
Instead, it prints March twice. http://jsfiddle.net/h69gm04g/2/
November
October
September
August
July
June
May
April
March
March
February
HTML
<div id="test"></div>
Javascript
monthNames = [ "January", "February", "March", "April", "May", "June","July", "August", "September", "October", "November", "December" ];
d = new Date();
for (i = 0; i < 12; i++) {
d.setMonth(d.getMonth() - 1);
monthName = monthNames[d.getMonth()];
$('#test').append(monthNames[d.getMonth()] + "<br>");
}
What am I doing wrong?
Nice one! Took me a while.
The reason for this is that today is the 29th. Since your date object is set to the current day implicitly and February only had 28 days in 2013, you see March printed twice. Fix this by setting the optional day parameter:
d.setMonth(d.getMonth() - 1, 1);
That's because today happens to be the 29th, and when you get to february the 29th it will wrap over into march.
Set the date to the 1st (or any other date that is less than 29), then it works for all months:
d = new Date();
d.setDate(1);
d.setMonth(d.getMonth() - 1);
Demo: http://jsfiddle.net/h69gm04g/3/
I don't think there's any reason for answers that manipulate a Date object on each iteration. Once we know the current month, all we need to do is iterate the list backwards, wrapping around at the end. That's a job for %. Unfortunately, % does not do a true mathematical mod operation, and can return a negative value, so the easiest implementation is to ensure that the value is positive by adding an additional 12 to it:
var month = new Date().getMonth();
for (i = 1; i <= 12; i++) {
$('#test').append(monthNames[(12 + month - i) % 12] + "<br>");
}
(JSFiddle)
Try this http://jsfiddle.net/oLp9hegk/:
monthNames = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ];
m = (new Date()).getMonth();
for (var i = 0; i < 12; i++) {
$('#test').append(monthNames[(m-i+11)%12] + "<br>");
}

Categories

Resources