SGN
SGN

Reputation: 341

Default date value to 9999/12/31 in angularjs

I want to pre fill by date field value to 9999/12/31. I have tried the below code

HTML

<div class="col-md-1">
  <datepicker date-format="yyyy-MM-dd">
      <input
        id="endDate"
        type="date"
        class="form-control"
        ng-model="entity.endDate"
        placeholder="yyyy-MM-dd
        ng-required="true"
        ng-disabled="formName == 'VIEWX'"
      >
  </datepicker>
</div>

Controller

$scope.entity = {
  endDate: new Date(9998, 12, 31)
};

I get the prefilled value as '10000-01-31'

Upvotes: 0

Views: 3521

Answers (1)

ryanyuyu
ryanyuyu

Reputation: 6486

Javascript dates can be dumb. The Date object uses 0-indexed months. From the documentation (emphasis mine):

Note: Where Date is called as a constructor with more than one argument, if values are greater than their logical range (e.g. 13 is provided as the month value or 70 for the minute value), the adjacent value will be adjusted. E.g. new Date(2013, 13, 1) is equivalent to new Date(2014, 1, 1), both create a date for 2014-02-01 (note that the month is 0-based).

This is further supported by the Date.getMonths() method which mentions

The getMonth() method returns the month in the specified date according to local time, as a zero-based value (where zero indicates the first month of the year).

The correct date for December 31, 9999 is

new Date(9999, 11, 31);

Plnkr demo

Upvotes: 2

Related Questions