1

I have a html span that display a date using moment.js in the page:

<span data-bind="text: moment(new Date(dueDate())).format('MM/DD/YYYY')"></span>

It's working fine apart if the dueDate() property is an empty string, If it's an empty string I'm getting:

01/01/1900

How can avoid that?

This is the entire div:

<div class="col-md-8">
    <ul>
      <li>DATE <span data-bind="text: moment(new Date(sDate())).format('MM/DD/YYYY')"></span></li>
      <li>Due date <span></span><span data-bind="text: moment(new Date(dueDate())).format('MM/DD/YYYY')"></span>
           <p>Days Remaining: <span class="days-remaining" data-bind="text: daysRemaining"></span></p>
      </li>
      <li>Date 2 <span></span><span data-bind="text: moment(new Date(date2())).format('MM/DD/YYYY')"></span>
           <p>Days Remaining: <span class="days-remaining" data-bind="text: daysRemaining"></span></p>
      </li>
    </ul>
</div>
user3378165
  • 6,546
  • 17
  • 62
  • 101

1 Answers1

3

You will have to add a check. If value exists, then parse value, else show blank.

this.getDateInFormat = function(str){
  var d = moment(str, DEFAULT_FORMAT);
  return str && d.isValid() ? d.format('MM/DD/YYYY') : '';
}

As commented before, you should move all parsing logic to your viewModel. This way your code is generic and your view is clean.

JSFiddle.

Rajesh
  • 24,354
  • 5
  • 48
  • 79