Reputation: 1895
I am binding a JSON object to a query template and I need to change how the date is being displayed.
In the JSON - I have the following key/value "dateOfTheMonth": "10-11-2015” and I need to do two things.
Display the date in the template like this “1st”, “2nd”, “3rd" - so just the day and appending the correct ordinal indicator (“st, nd, rd, th”)
Also keep the original format for use in a data attribute
Here the JSON...
"data": {
"currentMonth": "November",
"calendar": [
{
"dateOfTheMonth": "1-11-2015",
"isDateUnavailable": true,
"isDateSoldOut": false,
},
{
"dateOfTheMonth": “2-11-2015",
"isDateUnavailable": true,
"isDateSoldOut": false,
}
]
}
The function I use to get the JSON data (from an API) and bind it to a template
}
getDays(function (data) {
$("#template").tmpl(data.data.calendar).appendTo("#week");
});
And this is the template:
<script id="template" type="text/html">
<div class="day-container" data-arrival-Date=“${dateOfTheMonth}">
${dateWithOrdinal} // so here would display 1st, 2nd etc
</div>
</script>
Any help is appreciated.
Upvotes: 1
Views: 271
Reputation: 707
$(document).ready(function() {
var indate="1-11-2015";//your date here
var parts = indate.split('-');
function ordinal_suffix_of(i) {
var j = i % 10,
k = i % 100;
if (j == 1 && k != 11) {
return i + "st";
}
if (j == 2 && k != 12) {
return i + "nd";
}
if (j == 3 && k != 13) {
return i + "rd";
}
return i + "th";
}
var opdate = ordinal_suffix_of(parts[0]) + "-" +parts[1] + "-" +parts[2];
document.getElementById("demo").innerHTML =opdate;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="demo"></div>
Upvotes: 1