2012-07-25 199 views

回答

2

對於字符串:

curdate.substr(0, 6)+(curdate.substr(6)-1); 

如果你會使用一個Date object,你可以輕鬆減去一年與set[Full]Year方法。

30

您需要使用getFullYear()

,然後產生新的日期

var d = new Date(2012, 7, 25); 
d.setFullYear(d.getFullYear() - 1); 
+0

有關詳細信息,請參閱https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date/ – Sphvn 2012-07-25 12:32:26

+6

+1(月份應該爲6,以便與示例匹配) – 2012-07-25 12:40:13

+0

謝謝@AlexK。,示例中的日期是7月(0123).. – 2012-07-25 12:45:44

3

使用此:

var date = new Date(); 
var intYear = date.getFullYear() - 1; 
0

,以免日後對象(如果這是OP希望):

var currDate = '25-07-2012'; 
var dateParts = currDate.split('-'); 
dateParts[2] = parseInt(dateParts[2], 10) - 1; 
alert(dateParts.join('-'));​ 
+1

不適合閏年和2月29日 – 2017-01-19 05:51:19

2

Datepicker允許您將一個數字作爲minDate選項,並將其用作當前日期的偏移量。所以你可以寫:

minDate: -365 

指定1年前。不過,這並沒有考慮到閏年。

0
var today = new Date(); 
var curyear = today.getFullYear(); 
var curyearMonth = today.getMonth() + 1; 
var curyearDay = today.getDate(); 
var lastYear = curyear - 1; 
if ((curyearMonth == 2) && (curyearDay == 29)) { 
    curyearDay = 28; 
} 

var lastYearDisplay = ("0000" + lastYear.toString()).slice(-4) + "-" + ("00" + curyearMonth.toString()).slice(-2) + "-" + ("00" + curyearDay.toString()).slice(-2); 
alert("LastWeekDate : " + lastYearDisplay); 
-1
var date = CALC.today(); //(function in my dev-enviro - gives today's date) 
var year = formatDate(date, 'yyyy'); //year is 2016 
year = parseInt(year);    //make sure '2016' becomes an integer 
year = year -1;      // var year is now: 2015. 

//its been a while, but that's what I did from memory. 
-1
function getTodayDate() { 
     var today = new Date(); 
     var dd = today.getDate(); 
     var mm = today.getMonth() + 1; //January is not 0! 
     var yyyy = today.getFullYear(); 
     if (dd < 10) { dd = '0' + dd } 
     if (mm < 10) { mm = '0' + mm } 
     today = yyyy + '-' + mm + '-' + dd; 
     return today; 
    }; 
    function getYearAgo(){ 
    var lastYear = new Date(); 
    var dd = lastYear.getDate(); 
    var mm = lastYear.getMonth() + 1; //January is not 0! 
    var yyyy = lastYear.getFullYear(getTodayDate) - 1; 
    if (dd < 10) { dd = '0' + dd } 
    if (mm < 10) { mm = '0' + mm } 
    lastYear = yyyy + '-' + mm + '-' + dd;  
    return lastYear; 
    } 
3

試試這個

var d = new Date(); 
var pastYear = d.getFullYear() - 1; 
d.setFullYear(pastYear); 
console.log(d); 
相關問題