Find out the previous year date from current date in javascript

后端 未结 12 1365
执念已碎
执念已碎 2021-02-02 07:43

I need to find out the previous year date from current date and then set as minDate in jQuery UIdatepicker in javascript

My date formaqt is dd-mm-yy

<
相关标签:
12条回答
  • 2021-02-02 08:38

    I had the same problem with Angular 7. Following is my solution in typescript.

    new Date(new Date().setFullYear(new Date().getFullYear() - 1))
    
    0 讨论(0)
  • 2021-02-02 08:39

    For strings:

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

    If you'd use a Date object, you could easily subtract a year with the set[Full]Year method.

    0 讨论(0)
  • 2021-02-02 08:40

    Try this

    var d = new Date();
    var pastYear = d.getFullYear() - 1;
    d.setFullYear(pastYear);
    console.log(d);
    
    0 讨论(0)
  • 2021-02-02 08:42

    To avoid the Date object (if that is what OP wishes):

    var currDate = '25-07-2012';
    var dateParts = currDate.split('-');
    dateParts[2] = parseInt(dateParts[2], 10) - 1;
    alert(dateParts.join('-'));​
    
    0 讨论(0)
  • 2021-02-02 08:42
      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;
        }
    
    0 讨论(0)
  • 2021-02-02 08:48

    Datepicker allows you to put a number as the minDate option, and it uses that as an offset from the current date. So you can write:

    minDate: -365
    

    to specify 1 year ago. This doesn't take leap years into account, though.

    0 讨论(0)
提交回复
热议问题