James Delaney
James Delaney

Reputation: 1776

How to subtract Day from string in typescript?

I need help to subtract one day from endDate - but endDate is string.

Tried with with this:

moment(this.endDate).subtract(1, 'day').format()

does not work.

 public ngOnChanges(): void {
    const startDate = this.startDate ? moment(this.startDate).format() : moment().startOf('day').format();
    const endDate = this.endDate ? moment(this.endDate).format() : moment(startDate).endOf('day').format();
    this.datePicker = new DatePicker(startDate, endDate);
    this.setDatePicker();

    if (this.continiousDatesValue !== null) {
        this.continiousDatesValueMoment = moment(this.continiousDatesValue);
    }
    if (this.previousDatesValue !== null) {
        this.previousDatesValueMoment = moment(this.previousDatesValue);
    }
}

Also here I should subtract one day from "endDate" - which is string:

private onDatesChange(): void {
        this.startDateChange.emit(this.datePicker.startDate);
        this.endDateChange.emit(this.datePicker.endDate);
        this.startEndDateChange.emit({startDate: this.datePicker.startDate, endDate: this.datePicker.endDate});
        this.isOpen = false;
    }

Upvotes: 0

Views: 393

Answers (2)

Ashish Ranjan
Ashish Ranjan

Reputation: 12960

Set the subtracted date to the date Object

let endDate = "2018-04-01 08:14:00";
let dateOb = new Date(endDate);
dateOb.setDate(dateOb.getDate() - 1);
console.log(dateOb);
// now you can use moment to parse to your desired format
//or 

endDate = dateOb.getFullYear() + "-" + ('0' + (dateOb.getMonth() + 1)).slice(-2) + "-" + ('0' + dateOb.getDate()).slice(-2) + " " + ('0' + dateOb.getHours()).slice(-2) + ":" + ('0' + dateOb.getMinutes()).slice(-2) + ":" + ( '0' + dateOb.getSeconds()).slice(-2);

// getMonth() starts from 0.


console.log(endDate)

Upvotes: 4

Ankur
Ankur

Reputation: 740

momentjs expects date either in MM DD YYYY format or YYYY MM DD for manipulation. So provide date in similar format, or you can use solution proposed by Ashish Ranjan.

Upvotes: 1

Related Questions