热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

如何获得前一年的月份?

如何解决《如何获得前一年的月份?》经验,为你挑选了1个好方法。

我试着根据当月来得到上个月.但问题发生在"年"不是2017年.

在此输入图像描述

那我怎么能得到上一年的月份?下面的代码将描述我想要的内容,如果有人知道如何获取它,请告诉我方法.谢谢 :)

var mOnth= new Array();
		month[0] = "January";
		month[1] = "February";
		month[2] = "March";
		month[3] = "April";
		month[4] = "May";
		month[5] = "June";
		month[6] = "July";
		month[7] = "August";
		month[8] = "September";
		month[9] = "October";
		month[10] = "November";
		month[11] = "December";

		var cur_mOnth= new Date();
		var cur_month_now = month[cur_month.getMonth()];
		var pre_month_1 = month[cur_month.getMonth()-1];
		var pre_month_2 = month[cur_month.getMonth()-2];
		var pre_month_3 = month[cur_month.getMonth()-3];
		var pre_month_4 = month[cur_month.getMonth()-4];
		var pre_month_5 = month[cur_month.getMonth()-5];

		document.getElementById("cur_month").innerHTML = cur_month_now;
		document.getElementById("pre_month_1").innerHTML = pre_month_1;
		document.getElementById("pre_month_2").innerHTML = pre_month_2;
		document.getElementById("pre_month_3").innerHTML = pre_month_3;
		document.getElementById("pre_month_4").innerHTML = pre_month_4;
		document.getElementById("pre_month_5").innerHTML = pre_month_5;



1> gurvinder372..:

你得到这个未定义因为month[-1]而且month[-2]undefined

您需要在日期对象中实际执行日期操作,而不是仅从索引中获取日期.

使用此方法获取上个月的日期

function getPrevMonth(date) {
  date.setMonth(date.getMonth() - 1);
  return date;
}

根据需要多次调用此方法.

演示

function getPrevMonth(date) {
  date.setMonth(date.getMonth() - 1);
  return date;
}

var mOnth= new Array();
month[0] = "January";
month[1] = "February";
month[2] = "March";
month[3] = "April";
month[4] = "May";
month[5] = "June";
month[6] = "July";
month[7] = "August";
month[8] = "September";
month[9] = "October";
month[10] = "November";
month[11] = "December";

var cur_mOnth= new Date();
var cur_month_now = month[cur_month.getMonth()];
var pre_month_1 = month[getPrevMonth(cur_month).getMonth()];
var pre_month_2 = month[getPrevMonth(cur_month).getMonth()];
var pre_month_3 = month[getPrevMonth(cur_month).getMonth()];
var pre_month_4 = month[getPrevMonth(cur_month).getMonth()];
var pre_month_5 = month[getPrevMonth(cur_month).getMonth()];

document.getElementById("cur_month").innerHTML = cur_month_now;
document.getElementById("pre_month_1").innerHTML = pre_month_1;
document.getElementById("pre_month_2").innerHTML = pre_month_2;
document.getElementById("pre_month_3").innerHTML = pre_month_3;
document.getElementById("pre_month_4").innerHTML = pre_month_4;
document.getElementById("pre_month_5").innerHTML = pre_month_5;

推荐阅读
author-avatar
柳辰光
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有