methods/format-date.js

  1. import _config from './../lib/config'
  2. /**
  3. * @method
  4. * @memberof ecomUtils
  5. * @name formatDate
  6. * @description Parse date to locale formatted string.
  7. * @param {string|object} date - Date object or ISO string, or body object (order, product...)
  8. * @param {string} [lang=$ecomConfig.get('lang')] - Snake case language code, eg.: 'en_us', 'pt_br'
  9. * @param {object} [options] - Options object for `toLocaleDateString` function
  10. * @returns {string}
  11. *
  12. * @example
  13. * const notification = { datetime: '2019-06-19T03:35:52.811Z', content: {api_event: {resource: 'orders'}}}
  14. * ecomUtils.formatDate(notification, 'pt-br')
  15. * // => "19/06/2019"
  16. */
  17. const formatDate = (date, lang = _config.get('lang'), options) => {
  18. if (typeof date === 'object' && date !== null) {
  19. if (typeof date.getTime !== 'function') {
  20. // expected to be a body (product, category, brand...) object
  21. date = new Date(date.datetime || date.updated_at || date.created_at)
  22. }
  23. } else {
  24. // parse to Date object
  25. date = new Date(date)
  26. }
  27. if (!isNaN(date.getTime())) {
  28. try {
  29. // return locale date string
  30. // lang code format: pt-br, en-us...
  31. return date.toLocaleDateString(lang.replace('_', '-'), options)
  32. } catch (err) {
  33. console.error(err)
  34. }
  35. }
  36. // fallback returning empty string by default
  37. return ''
  38. }
  39. export default formatDate