user3272686
user3272686

Reputation: 849

format a date in a knockout foreach statement

I am having an issue formatting a date field from a knockout model:

<table class="signatures">
    <tbody data-bind="foreach: $root.signatures()">
        <tr>
            <td><span data-bind="text: DateSigned"></span></td>
        </tr>
    </tbody>
</table>

This is the result that I get:

/Date(-62135571600000)/ 

Upvotes: 1

Views: 1597

Answers (1)

Evan Larsen
Evan Larsen

Reputation: 9965

What you have is a Javascript Date which is just the milliseconds from January 1st 1970. You need to create a formatter that will format the javascript date into something more readable to the user.

Depending if you are using UTC dates you will need to check the local of the user before formatting or just let the user know which timezone your dates are in.

Here is a MDN article on all the functions that javascript inherently has that you can perform on your date object.

So, I would create a date function that formats the date for you.

function formatDate(odate) {
  var date = ko.util.unwrapObservable(odate);
  var year = date.getYear();
  var month = date.getMonth() + 1;
  var day = date.getDate();
  return year + '/' + month + '/' + day;
}

then inside your view you could:

<table class="signatures">
    <tbody data-bind="foreach: $root.signatures()">
        <tr>
            <td><span data-bind="text: formatDate(DateSigned)"></span></td>
        </tr>
    </tbody>
</table>

Upvotes: 4

Related Questions