nanonerd
nanonerd

Reputation: 1984

knockout - how to bind date only

I have an array, one key is createDate. In a foreach looping of the array, I pull the createDate value via a knockout text binding.

<span data-bind="text: createDate"></span>

The value displays: '2013-04-24T16:29:00.38' ... this is the way it exists in the database. Is there a way to format (within the binding) to show just the date only? Or do I have to save it as date only in the database to achieve this?

E.g., you can use the following to set 2 decimals:

<span data-bind="text: price.ToFixed(2)"></span>

Is there something simple such as this to only display: '2013-04-24'

Thanks in advance !

Upvotes: 5

Views: 17054

Answers (3)

greens
greens

Reputation: 1

thanx it worked for me to display time only :

 <td data-bind="text:moment(OpeningTime()).format('h:mm:ss a')"></td>

Upvotes: 0

Zack Yang
Zack Yang

Reputation: 399

Add this javascript:

String.prototype.Format = function (fmt) {
var myDate = this;
var o = {
    "M+": myDate.getMonth() + 1,
    "d+": myDate.getDate(),
    "h+": myDate.getHours(),
    "m+": myDate.getMinutes(),
    "s+": myDate.getSeconds(),
    "q+": Math.floor((myDate.getMonth() + 3) / 3),
    "S": myDate.getMilliseconds()
};
if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (myDate.getFullYear() + "").substr(4 - RegExp.$1.length));
for (var k in o)
    if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
return fmt;

};

Then you can use like this:

<span data-bind="text: createDate().Format('MM/DD/YYYY')"></span>

Upvotes: -2

Jason Haley
Jason Haley

Reputation: 3800

For me the key is moment.js

You can do something as simple as this:

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

Or you could write a binding helper like this guy does, so it would be something like:

<span data-bind="dateString: createDate, datePattern: 'MM/DD/YYYY'"></span>

Upvotes: 18

Related Questions