Skip to content

Instantly share code, notes, and snippets.

@AmboMaya
Last active April 12, 2020 00:47
Show Gist options
  • Save AmboMaya/2c4ae1ea0997604e6073ad0bfc1d1907 to your computer and use it in GitHub Desktop.
Save AmboMaya/2c4ae1ea0997604e6073ad0bfc1d1907 to your computer and use it in GitHub Desktop.
Ember JS date helper

This helper is used to display the following format : Apr 21, 2019 00:21.38 AM

In util directory, create date.js file

  const MONTH_NAMES = [
    'Jan',
    'Feb',
    'Mar',
    'Apr',
    'May',
    'Jun',
    'Jul',
    'Aug',
    'Sep',
    'Oct',
    'Nov',
    'Dec',
  ];

  /**
   * Pad a numeric value with zeroes, if needed
   *
   * @example
   *
   * padLeadingZeroes(13, 4); // "0013"
   * padLeadingZeroes(130, 2); // "130"
   *
   * @param {number} val value
   * @param {number} digits number of digits to pad
   * @returns {string}
   */

  function padLeadingZeroes(val, digits) {
    let valString = `${val}`;
    while (valString.length < digits) valString = 0 + valString;
    return valString;
  }

  /**
   * Create a string representation of a Date
   * @param {string|number|Date} date
   * @returns {string}
   */
  export function dateToString(date) {
    if (
      !(
        typeof date === 'string' ||
        typeof date === 'number' ||
        date instanceof Date
      )
    )
      return null;
    const d = new Date(date);
    const ampm = d.getHours() > 12 ? 'PM' : 'AM';
    return `${
      MONTH_NAMES[d.getMonth()]
    } ${d.getDate()}, ${d.getFullYear()} ${padLeadingZeroes(
      d.getHours() % 12,
      2
    )}:${padLeadingZeroes(d.getMinutes(), 2)}.${padLeadingZeroes(
      d.getSeconds(),
      2
    )} ${ampm}`;
  }

Generate a helper called format-timestamp.js

  import { helper } from '@ember/component/helper';
  import { dateToString } from '../utils/date';

  export default helper(function formatTimestamp([date]) {
    const str = dateToString(date);
    return str;
  });

To use format-timestamp in template file {{format-timestamp '4/21/2019 12:21:38'}}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment