[英]Printing 3 year calendar in months staring from the current month
I am getting the current date in javascript and then I convert it to the current month. 我在javascript中获取当前日期,然后将其转换为当前月份。 Based on the current month (9 now), I want to print the month calendar for the last 3 years backwards. 基于当前月份(现在为9),我想向后打印过去3年的月份日历。 So, if we have September 2013, the following has to be printed: 因此,如果我们有2013年9月,则必须打印以下内容:
08 09 10 11 12 2010
01 02 03 04 05 06 07 08 09 10 11 12 2011
01 02 03 04 05 06 07 08 09 10 11 12 2012
01 02 03 04 05 06 07 08 2013
I have a general idea how to print the first line, but I'm struggling how to print the rest of the calendar. 我对如何打印第一行有一个大致的了解,但是我在努力如何打印日历的其余部分。 Here is my code for the first line (2013): 这是我第一行(2013年)的代码:
function printCalendarRows(){
var d = new Date();
var n = (d.getMonth()) + 1;
var twelve = 12;
for(var i = n; i <= 12; i++){
for(var j = 12; j >= n; j--){
console.log(i);
console.log(j);
}
}
}
Any recommendations? 有什么建议吗? Thanks 谢谢
function calRows() {
var date,
now = new Date(),
str = "";
for (var i = -37;i++;) {
date = new Date(now.getFullYear(), now.getMonth() + i - 1, 1)
month = ("0" + (date.getMonth() + 1)).slice(-2);
str += month + " " + (+month % 12 == 0 ? date.getFullYear() + "\n" : "")
}
return str + date.getFullYear();
}
console.log (calRows()) /*
08 09 10 11 12 2010
01 02 03 04 05 06 07 08 09 10 11 12 2011
01 02 03 04 05 06 07 08 09 10 11 12 2012
01 02 03 04 05 06 07 08 2013 */
Or if you prefer, the same without assigning a new Date object in the loop. 或者,如果愿意,也可以在循环中不分配新的Date对象的情况下进行相同操作。
function calRows() {
var date,
now = new Date(),
first = new Date(now.getFullYear(), now.getMonth() -37, 1),
monthYear = [first.getMonth(),first.getFullYear()]
str = "";
for (var i = -37;i++;) {
month = ("0" + (++monthYear[0])).slice(-2);
str += month + " " + (+month % 12 == 0 ? (monthYear[0]=0,monthYear[1]++) + "\n" : "")
}
return str + monthYear[1]
}
Check if this is what you want 检查这是否是您想要的
function printCalendarRows(){
var d = new Date();
var o = new Date();
o.setMonth( (d.getMonth()) - 36); //or o.setFullYear( (d.getFullYear()) - 3);
var currnt;
while (o < d)
{
currnt = o.getMonth();
console.log(currnt);
if (currnt == 11)
{
console.log(o.getFullYear());
}
o.setMonth(currnt+1);
}
if (d.getMonth() != 11)
{
console.log(d.getFullYear());
}
alert("Date:"+ d + "Month:" + d.getMonth());
}
I would use momentjs : 我会使用momentjs :
function printCalendarRows(){
var d = moment().subtract('months', 37);
var y = d.format("YYYY");
var n = moment().format("MM/YYYY");
var log = "";
while(d.format("MM/YYYY") != n) {
if (d.format("YYYY") != y) {
console.log(log + y + "\r\n");
y = d.format("YYYY");
log = "";
}
log += d.format("MM") + " ";
d = d.add("months", 1);
}
console.log(log + d.format("YYYY"));
}
printCalendarRows();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.