Amr Ammar
Amr Ammar

Reputation: 43

Compare html type="date" with typescript new Date() object

I have an html code

<div class="form-group row">
          <label class="col-sm-2 col-form-label">Due date: </label>
          <div class="col-sm-10">
            <input type="date" class="form-control" #due_date>
          </div>
</div>

and my typscript code is like this but it never enters the condition, so what should I do?

if(element.due_date <= new Date()){
    //if(element.due_time <= new Date().toLocaleTimeString())
    console.log(element);
    element.notify = true;
  } 

Upvotes: 2

Views: 580

Answers (2)

Shaya
Shaya

Reputation: 2932

It could quickly get done using moment.js. I would keep the input model as an ISO string and have moment.js parse it when it compares the dates:

moment(dateInISO).isAfter(anotherDateInISO); // true

Or let moment.js take care of your own different date types :)

Upvotes: 1

Somnath Sinha
Somnath Sinha

Reputation: 672

According to the template, your component code should be like

export class SomeComponent {
  @ViewChild('due_date') due_date: ElementRef;

  someMethod() {
    const inputDate = new Date(this.due_date.nativeElement.value);
    if (inputDate <= new Date()) {
      //if(element.due_time <= new Date().toLocaleTimeString())
      console.log(this.due_date.nativeElement.value);
      // element.notify = true;
    } 
  }
}

Upvotes: 0

Related Questions