如何根据计数

时间:2017-06-07 12:05:29

标签: javascript

如何在javascript中获取正确的月份。我不想为此使用任何插件。



var date = new Date();
var month = date.getMonth();
// value is 06 current month;

var month = date.getMonth() + 15;
// now value is 21




这里,如果getMonth()计数超过12,则意味着如何获得正确的月份。 如果超过12意味着我需要增加年份也是对的。

例如,



// assume current month December
var month = date.getMonth()+3;  // value is 14




我想将这个月显示为" 03" (游行)。请帮帮我怎样才能做到这一点

4 个答案:

答案 0 :(得分:2)

使用%12。将用12减去月份.Remaining将显示在

注意: 请记住月份值从0开始0=January



var date = new Date();
var month = date.getMonth();
console.log('default month value ='+month)
month = (date.getMonth() + 15) % 12;
console.log(month)




答案 1 :(得分:1)



var date = new Date();
var month = date.getMonth();

var monthNames = ["January", "February", "March", "April", "May", "June",
  "July", "August", "September", "October", "November", "December"
];

var month = date.getMonth() + 15;

var result = new Date(date.getYear(),month,date.getDay()).getMonth();

console.log(result, monthNames[result]);




答案 2 :(得分:0)

您可以设置月份,使其也改变年份:

var date=new Date();
alert(date+"");
date.setMonth(date.getMonth() + 15);
alert(date+"");

js引擎已经处理了月溢出......

答案 3 :(得分:0)

好像每个人的回答都不正确。

date.getMonth()返回月份的整数等值,从零开始,因此new Date().getMonth()返回5而不是6.因此,month + 15 = 20,而不是21。

从6月开始,我们增加了15个月:

1. July
2. August
3. Sept
4. Oct
5. Nov
6. Dec
7. Jan
8 Feb
9 Mar
10 Apr
11 May
12 June
13 July
14 Aug
15 Sept

所以,它是9月,而不是8月!!!



var date = new Date(),
  monthNames = ["January", "February", "March", "April", "May", "June",
    "July", "August", "September", "October", "November", "December"
  ];
var month = date.getMonth(); //current month is 5, 0 based. january = 0, feb = 2, .... dec = 11
//console.log(month);
month = date.getMonth() + 15; //value becomes 20, not 21
//console.log(month);

var newDT = new Date(date.getFullYear(), month, date.getDate());
console.log("today's date is:" + date.getDate());

var newMonth = newDT.getMonth();
console.log("Current month plus 15 months is " + (newMonth + 1));
console.log("Month name is " + monthNames[newMonth]); //don't need to add 1 since our monthNames is zero-based