Gitter migration: Setup redirects (rollout pt. 3)
[gitter.git] / shared / time / time-format.js
blob8f27917a33691a37d75df63e80aba49b7f1fb6ae
1 'use strict';
3 var moment = require('moment');
5 // checks whether two moment times are on the same date
6 const isSameDay = (a, b) =>
7 a.date() === b.date() && a.month() === b.month() && a.year() === b.year();
9 /**
10 * Returns an abbreviated time format.
12 * * If the date is today, returns the time
13 * * If the date is this year, returns the full date without a year
14 * * Otherwise returns the full
16 * option.now makes testing easier
18 module.exports = function timeFormat(time, { lang, tzOffset, compact, now, forceUtc } = {}) {
19 if (!time) return '';
21 const momentTime = moment(time);
22 if (lang) {
23 momentTime.locale(lang === 'en' ? 'en-gb' : lang);
26 const parsedOffset = forceUtc ? 0 : tzOffset;
27 if (parsedOffset !== undefined) {
28 momentTime.utcOffset(-parsedOffset);
31 const today = moment(now).utcOffset(momentTime.utcOffset());
33 // UTC suffix is used in archive to indicate the timestamp not being local time
34 const utcSuffix = forceUtc ? ' [UTC]' : '';
35 const formatHoursAndMinutes = compact ? '' : ' HH:mm';
36 if (isSameDay(momentTime, today)) {
37 // TODO: deal with american `10:20 PM`
38 return momentTime.format(`HH:mm${utcSuffix}`);
41 if (momentTime.year() === today.year()) {
42 return momentTime.format(`MMM DD${formatHoursAndMinutes}${utcSuffix}`);
45 return momentTime.format(`MMM DD YYYY${formatHoursAndMinutes}${utcSuffix}`);