我的日期定义为"Jul 2015"
或"Aug 2016"
,我需要获得它们的去年版本。
例如:
getLastYear("Jul 2015")
return: Jul 2014
我如何在JavaScript中执行此操作?到目前为止,我的尝试无效:
var date = new Date('Jul 2015');
var new_date = new Date().setYear(date .getFullYear()-1);
alert(new_date );
// return a timestamp value e.g. 1404505003030
答案 0 :(得分:2)
你几乎得到它,你错过了将timestamp
转换为date
var date = new Date('Jul 2015');
var new_date = new Date().setYear(date .getFullYear()-1);
new_date = new Date(new_date)
要设置日期格式,请使用:
var months = [
"Jan", "Feb", "Mar",
"Apr", "May", "Jun", "Jul",
"Aug", "Sep", "Oct",
"Nov", "Dec"
];
var monthIndex = new_date.getMonth();
var month = months[monthIndex]
var year = new_date.getYear();
var final_date = year + month
console.log(final_date) // you will get 'Jul 2014'
答案 1 :(得分:0)
var date = new Date('Jul 2015');
date.setYear(date .getFullYear()-1);
alert(date);
应该为你做。 setYear返回一个值,并在日期上设置年份,因此您需要相应地使用它。
答案 2 :(得分:0)
你需要做这样的事情,你可以根据你的要求编辑月份数组,
function getLastYear(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 d = (new Date(new Date('1 '+date).setYear(new Date('1 '+date).getFullYear() -1)))
console.log(d);
return month[d.getMonth()]+' '+d.getFullYear()
}
getLastYear("July 2016") //"July 2015"
答案 3 :(得分:0)
你实际上不需要日期对象。你也可以使用字符串函数:
var dateString = "Jul 2015";
var newString = dateString.substr(0,dateString.length - 4)+parseInt(dateString.substr(dateString.length - 4)-1);
alert(newString);
答案 4 :(得分:0)
var date = new Date('Jul 2015');
var new_date = new Date(date .getFullYear()-1,date.getMonth());
var year = new_date.getFullYear();
Date.prototype.getMonthName = function() {
var monthNames = [ "Jan", "Feb", "Mar", "April", "May", "Jun",
"Jul", "Aug", "Sept", "Oct", "Nov", "Dec" ];
return monthNames[this.getMonth()];
}
var month = new_date.getMonthName(new_date.getMonth());
alert(month+" "+year );
你也可以使用javascript的时刻库来转换为不同的格式http://momentjs.com/ reference: