2014-10-10 18:54:07 +04:00
|
|
|
// # Date Helper
|
|
|
|
// Usage: `{{date format="DD MM, YYYY"}}`, `{{date updated_at format="DD MM, YYYY"}}`
|
|
|
|
//
|
2016-02-02 10:04:40 +03:00
|
|
|
// Formats a date using moment-timezone.js. Formats published_at by default but will also take a date as a parameter
|
2014-10-10 18:54:07 +04:00
|
|
|
|
2021-05-04 18:49:35 +03:00
|
|
|
const {SafeString} = require('../services/proxy');
|
2019-04-02 09:36:13 +03:00
|
|
|
const moment = require('moment-timezone');
|
2021-03-05 16:35:31 +03:00
|
|
|
const _ = require('lodash');
|
2017-04-04 19:07:35 +03:00
|
|
|
|
2021-03-05 16:35:31 +03:00
|
|
|
module.exports = function (...attrs) {
|
|
|
|
// Options is the last argument
|
|
|
|
const options = attrs.pop();
|
|
|
|
let date;
|
2014-10-10 18:54:07 +04:00
|
|
|
|
2021-03-05 16:35:31 +03:00
|
|
|
// If there is any more arguments, date is the first one
|
|
|
|
if (!_.isEmpty(attrs)) {
|
|
|
|
date = attrs.shift();
|
2014-10-10 18:54:07 +04:00
|
|
|
|
2021-03-05 16:35:31 +03:00
|
|
|
// If there is no date argument & the current context contains published_at use that by default,
|
|
|
|
// else date being undefined means moment will use the current date
|
|
|
|
} else if (this.published_at) {
|
|
|
|
date = this.published_at;
|
2014-10-10 18:54:07 +04:00
|
|
|
}
|
|
|
|
|
2021-03-05 16:35:31 +03:00
|
|
|
// ensure that date is undefined, not null, as that can cause errors
|
|
|
|
date = date === null ? undefined : date;
|
|
|
|
|
|
|
|
const timezone = options.data.site.timezone;
|
2021-05-04 18:49:35 +03:00
|
|
|
const locale = options.data.site.locale;
|
|
|
|
|
2019-04-02 09:36:13 +03:00
|
|
|
const {
|
2021-03-05 16:35:31 +03:00
|
|
|
format = 'll',
|
2019-04-02 09:36:13 +03:00
|
|
|
timeago
|
|
|
|
} = options.hash;
|
|
|
|
|
|
|
|
const timeNow = moment().tz(timezone);
|
2021-03-05 16:35:31 +03:00
|
|
|
// Our date might be user input
|
|
|
|
let testDateInput = Date.parse(date);
|
|
|
|
let dateMoment;
|
|
|
|
if (isNaN(testDateInput) === false) {
|
|
|
|
dateMoment = moment.parseZone(date);
|
|
|
|
} else {
|
|
|
|
dateMoment = timeNow;
|
|
|
|
}
|
2014-10-10 18:54:07 +04:00
|
|
|
|
2018-01-09 16:50:57 +03:00
|
|
|
// i18n: Making dates, including month names, translatable to any language.
|
|
|
|
// Documentation: http://momentjs.com/docs/#/i18n/
|
|
|
|
// Locales: https://github.com/moment/moment/tree/develop/locale
|
2021-05-04 18:49:35 +03:00
|
|
|
dateMoment.locale(locale);
|
2018-01-09 16:50:57 +03:00
|
|
|
|
2014-10-10 18:54:07 +04:00
|
|
|
if (timeago) {
|
2021-03-05 16:35:31 +03:00
|
|
|
date = dateMoment.tz(timezone).from(timeNow);
|
2014-10-10 18:54:07 +04:00
|
|
|
} else {
|
2021-03-05 16:35:31 +03:00
|
|
|
date = dateMoment.tz(timezone).format(format);
|
2014-10-10 18:54:07 +04:00
|
|
|
}
|
2016-02-02 10:04:40 +03:00
|
|
|
|
2017-04-04 19:07:35 +03:00
|
|
|
return new SafeString(date);
|
2014-10-10 18:54:07 +04:00
|
|
|
};
|