date.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. 'use strict';
  2. const moment = require('moment-timezone');
  3. const isMoment = moment.isMoment;
  4. const isDate = require('lodash/isDate');
  5. function getMoment(date, lang, timezone) {
  6. if (date == null) date = moment();
  7. if (!isMoment(date)) date = moment(isDate(date) ? date : new Date(date));
  8. if (lang) date = date.locale(lang);
  9. if (timezone) date = date.tz(timezone);
  10. return date;
  11. }
  12. function toISOString(date) {
  13. if (date == null) {
  14. return new Date().toISOString();
  15. }
  16. if (date instanceof Date || isMoment(date)) {
  17. return date.toISOString();
  18. }
  19. return new Date(date).toISOString();
  20. }
  21. function dateHelper(date, format) {
  22. const config = this.config;
  23. const moment = getMoment(date, getLanguage(this), config.timezone);
  24. return moment.format(format || config.date_format);
  25. }
  26. function timeHelper(date, format) {
  27. const config = this.config;
  28. const moment = getMoment(date, getLanguage(this), config.timezone);
  29. return moment.format(format || config.time_format);
  30. }
  31. function fullDateHelper(date, format) {
  32. if (format) {
  33. const moment = getMoment(date, getLanguage(this), this.config.timezone);
  34. return moment.format(format);
  35. }
  36. return `${this.date(date)} ${this.time(date)}`;
  37. }
  38. function relativeDateHelper(date) {
  39. const config = this.config;
  40. const moment = getMoment(date, getLanguage(this), config.timezone);
  41. return moment.fromNow();
  42. }
  43. function timeTagHelper(date, format) {
  44. const config = this.config;
  45. return `<time datetime="${toISOString(date)}">${this.date(date, format, getLanguage(this), config.timezone)}</time>`;
  46. }
  47. function getLanguage(ctx) {
  48. return ctx.page.lang || ctx.page.language || ctx.config.language;
  49. }
  50. exports.date = dateHelper;
  51. exports.date_xml = toISOString;
  52. exports.time = timeHelper;
  53. exports.full_date = fullDateHelper;
  54. exports.relative_date = relativeDateHelper;
  55. exports.time_tag = timeTagHelper;
  56. exports.moment = moment;