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>");
}
Related
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.
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)
I got this value from a MySQL DB field: "september 9 # 08:00 - 17:00".
Can i change this client side to 9 september? I tried with JavaScript but i didn't come even close.
The date may change.
Desired result in browser: 9 september
Thank you,
That's a pretty uncommon output for a datetime value from the database. One solution is to simply strip all text after the # character - if you're sure the output format stays as is:
var datetime = 'september 9 # 19:20 - 20:00';
var result = datetime.substr(0, datetime.indexOf('#')).trim();
console.log(result); // outputs 'september 9'
var date = new Date(result);
var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
console.log(date.getDate(), months[date.getMonth()]); // outputs '9 September'
The values you want are in the string, so just reformat it:
var s = 'September 9 # 08:00 - 17:00';
var b = s.split(' ');
console.log(b[1] + ' ' + b[0]);
// You could even do
console.log(s.replace(/(\w+) (\d+)(.*)/, '$2 $1'));
// Or if you want to just swap the month and day and keep the rest
console.log(s.replace(/(\w+) (\d+)/, '$2 $1'));
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..
I have a problem with getting the correct days for each month in year 2014..
It shows that January and February has 31 days each, and March 28.
Im unable to fix this. Maybe you can come up with some tips or tricks? :)
EDIT:
I can see that my programme first month == 0 is collecting from december year 2013 which is very wierd, because i only refer to 2014 in the "Date" function.
Do you have any suggestions?
Here is my code:
The months and the days are in swedish, but I dont think that will be a problem..
function DaysInAMonth (month) {
return new Date(2014, month, 0).getDate();
}
function nameOfTheWeekdays(day) {
return [
"Måndag", "Tisdag", "Onsdag", "Torsdag", "Fredag", "Lördag", "Söndag"
][day];
}
function getMonthName(month) {
return [
"Januari", "Februari", "Mars", "April", "Maj", "Juni", "Juli", "Augusti", "September", "Oktober", "November", "December"
][month];
}
var month = 0;
var day = 0;
for (var i=0; i<12; i++) {
for (var x=0; x<DaysInAMonth(i); x++) {
var c = new Date(2014, i, x);
document.writeln( nameOfTheWeekdays(c.getDay()) + " " + (x+1) + " " + getMonthName(month));
day++;
}
month++;
}
Months in JavaScript dates are numbered 0 through 11, not 1 through 12. Indeed, your "DaysInAMonth()" function seems to rely on that fact.
The date 1 January 2014 is obtained from new Date(2014, 0, 1).
You can use an array to map month or day numbers into names:
function getMonthName(m) {
return [
"Januari", "Februari", "Mars", "April",
"Maj", "Juni", "Juli", "Augusti",
"September", "Oktober", "November", "December"
][m];
}