Search code examples
javascriptractivejs

Date conversion using Ractive.js


How do I convert this Epoch time value returned by a JSON end point to a time string like "Tue 19 Jan 11:14:07 SGT 2038"?

var ractive = new Ractive({
  el: '#container',

  template: '#template',

  data: {
    lastUpdated: 2147483647
  }
});
<script src="http://cdn.ractivejs.org/latest/ractive.js"></script>
<pre>$ date --date='@2147483647'	
Tue 19 Jan 11:14:07 SGT 2038
</pre>

<div id='container'></div>
<script id='template' type='text/ractive'>
  <h1>Time: {{Date(lastUpdated)}}</h1>
</script>

I don't want to use additional libraries like moment.js. Thanks!


Solution

  • Ractive doesn't have an opinion about how to format dates, but you can very easily add a custom formatter to the data object:

    var ractive = new Ractive({
      el: '#container',
      template: '<h1>Time: {{formatDate(lastUpdated)}}</h1>',
      data: {
        lastUpdated: 2147483647,
        formatDate: function ( date ) {
          // formatting code goes here...
        }
      }
    });
    

    Whenever lastUpdated changes, the formatter will be called again.