Display all 12 months serially but starting from the current month - javascript

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.

Related

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)

Coverting DATETIME string to time and date in words Javascript or jQuery

i have a datetime parameter in a string from an JSON object
like this-
datetime:"2015-04-15 09.00.00"
my goal is to convert it to:
"15 April 09:00"
(2015 can be included as well but not necessary)
After i will append in in 2 different places, date and time.
Any suggestions? Can't seem to find any good info apart from getting a plugin.
You can parse the month like the answer here:
https://stackoverflow.com/a/1643468/2498251
var monthNames = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
];
so for your case you can make something like this:
var d = new Date("2015-04-15 09:00:00");
var day = d.getDay();
var month = monthNames[d.getMonth()];
var year = d.getYear();
var hour = d.getHours();
var min = d.getMinutes();
var fullDatetime = day + ' ' + month + ' ' + hour + ':' + min;

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

How to Populate An Array of Month Number In jQuery - Javascript

Can you please take a look at this demo and let me know how I can dynamically populate the number of each month for current year in jQuery or JavaScript?
var monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var daysInMonth = [];
var d = new Date();
var n = d.getMonth();
for (var i = 0; i < monthNames.length; i++) {
daysInMonth.push(d.getMonth());
}
console.log(daysInMonth);
var monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var daysInMonth = [];
for (var i = 0; i < monthNames.length; i++) {
var year = 2014;
var month = new Date(monthNames[i] + " 01 "+ year).getMonth() + 1;
daysInMonth.push(new Date(year, month, 0).getDate());
}
console.log(daysInMonth);
DEMO http://jsfiddle.net/0mj2cxmt/7/
#Sam Battat's answer works too, but for a simple snippet of code that works on any year when called you could try this:
var thisDay = new Date();
var thisYear = thisDay.getYear();
var feb29th = new Date(thisYear, 1, 29);
var febDays = ((feb29th.getMonth() === 1) ? 29 : 28);
var dayCounts = [31,febDays,31,30,31,30,31,31,30,31,30,31];
Notes:
The number of days is hard coded for all months except February since they don't change
The feb29th variable above will actually become March 1st on years that don't have 29 days (e.g. non-leap years) and thus the month won't be "1"... defaulting the number of days back to 28
Update:
After running this perf test http://jsperf.com/leap-year-check it has become apparent that the "crafty" check for a leap year performance is nowhere near as good as basic math checks.
Thus I'd consider this to be even more efficient.
var thisDay = new Date();
var thisYear = thisDay.getYear();
var febDays = 28;
if((thisYear % 4 == 0) && (thisYear % 100 != 0) || (thisYear % 400 == 0)){
febDays = 29;
}
var dayCounts = [31,febDays,31,30,31,30,31,31,30,31,30,31];

Displaying my date to a specific format

I am having a little difficulty with this.How can I display a date value to format 10 September 2014 using Javascript.
What I am doing at the moment is
var dateAdded = new Date(parseInt(user.DateAdded.substr(6)));
which gives me Wed Sep 10 2014
duplicate of How to format a JavaScript date
but Marko's accepted answer there for you:
Taken from http://www.webdevelopersnotes.com/tips/html/javascript_date_and_time.php3:
<script type="text/javascript">
<!--
var m_names = new Array("January", "February", "March",
"April", "May", "June", "July", "August", "September",
"October", "November", "December");
var d = new Date();
var curr_date = d.getDate();
var curr_month = d.getMonth();
var curr_year = d.getFullYear();
document.write(curr_date + "-" + m_names[curr_month]
+ "-" + curr_year);
//-->
</script>
You can edit the array to use Jan, Feb, Mar, etc..

Categories

Resources