Search code examples
javascriptpikaday

Return selected date in Pikaday plugin, within the plugin?


I want to modify the JavaScript (no JQuery) Pikaday date selector to show the chosen date in a header area, above the calendar.

To do this I have created a new function to render the header areas HTML:

renderHeading = function(instance, c, year, month, days)
{
        var opts = instance._o;
        var html = '<div class="pika-heading">';
        html += '<h3 class="pika-heading-year">' + year + '</h3>';
        html += '<h1 class="pika-heading-date">' + opts.i18n.weekdaysShort[day] + ', ' + opts.i18n.monthsShort[month] + '</h1>';
        return html += '</div>';
},

This works fine - it displays the month and the year.

However, I cannot figure out how to get it show the selected day number. My goal is to get it to show something like "Mon 1st Dec 2016" but I cannot get the 'Mon' and '1' to show.

The best I've been able to do is create:

window.setDateProperty = this._o.field.value;

in the getDate function and return that in my HTML render function, but this only works after 2 clicks and seems messy.

Would anyone know the correct way of returning the date string to within a part of the plugin?


Solution

  • OK, I found that using the following got it:

    instance.getDate()
    

    From there I could use the methods of Date.parse to get the information I needed, eg:

    var dayOfWeek = instance.getDate().getDay();
    

    My full code:

     renderHeading = function(instance, c, year, month, days)
     {
    
        var dayOfMonth = instance.getDate().getDate(),
        dayOfWeek = instance.getDate().getDay(),
        opts = instance._o,
        html = '<div class="pika-heading">';
        html += '<h3 class="pika-heading-year">' + year + '</h3>';
        html += '<h1 class="pika-heading-date">' + opts.i18n.weekdaysShort[dayOfWeek] + ', ' + dayOfMonth +', ' + opts.i18n.monthsShort[month] + '</h1>';
        return html += '</div>';
     },