如何从Angular 2中的Date类型中减去一年?

时间:2016-05-18 14:30:13

标签: typescript angular datetimepicker

我想从Angular组件中的Date中减去一年。这是我的模板:

<input type="date" [value]="date" (change)="date=$event.target.value" class="form-control"
/>

相关课程:

export class appResultadosUtenteComponent {
    date: string;

    constructor() {
        this.date = new Date().toISOString().slice(0, 10);
    }
}

3 个答案:

答案 0 :(得分:10)

您可以使用Date#setFullYear将年份设置为小于Date#getFullYear的一年:

const now = new Date();
now.setFullYear(now.getFullYear() - 1);

document.write(now.toISOString().slice(0,10));

答案 1 :(得分:1)

我会使用时刻库​​来执行此操作:

以下是配置它的方法:

<script>
  System.configure({
    map: {
      (...)
      'moment': 'node_modules/moment/moment'
    },
    (...)
  });
</script>

答案 2 :(得分:0)

可以使用Moment.js

import * as moment from 'moment';

todayDate: Date = new Date();
lastDate = moment(this.todayDate).substract(1, 'year').format('YYYY-MM-DD').toString();