Search code examples
javascriptdateformattingpolymerpolymer-2.x

Polymer - format date in binded value


I have a tile inside a template and I want it to show a date:

  <template>
    <px-tile
        description=[[date]]
    </px-tile>
  </template>

Where date is a property of the element:

  date: {
    type: Date,
  }

This will however display the whole date and time, and I only want the date. So I'm trying to do:

  <template>
    <px-tile
        description=[[date.toLocaleDateString("en-US")]]
    </px-tile>
  </template>

But this doesn't work. How can I format the date in this setup?


Solution

  • For this you could arrang in px-tile.html something like:

    DEMO

    ...
    </style>
    <div>Date : [[localDate]]</div>
    ...
    
      date: {
        type: Date,
        observer:'_checkDate'
      }
    
    
    _checkDate(d) {
       if (d) {
             // you may set the options with this information: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString
             var options = { year: 'numeric', month: 'long', day: 'numeric' }; 
             this.set('localDate', d.toLocaleDateString('en-US', options))
       }
    }
    

    Keep the parent element same as your previous sample but change the attribute name as date that this will be property at child element:

     <template>
        <px-tile
            date=[[date]]>
        </px-tile>
      </template>