LoginSignup
4
4

More than 5 years have passed since last update.

moment.jsで午前1時30分を "25:30" という文字列で出力させる。

Posted at

実現したいこと

  • 午前(つまり深夜の)1時30分を、"01:30" ではなくて、"25:30" と表示させたい。

  • 時間を加える演算、例えば「25時30分の2.25時間後は、27時45分」ということも実現したい。

書いたコード

  • 上記の、実現したいことは、Moment.js にちょっと手を入れたらできるのでは?と思ったので、ざっくりスパイクしてみました。

  • 書いたコードは、以下のレポジトリにあります。

  • Momentに手を入れてるコードは以下の momentH25conf(startHour) です。

function momentH25conf(startHour) {

  // checking the parameter "startHour"
  if (!Number.isInteger(startHour)) return;
  if (startHour <= 0 || startHour > 12) return;

  // add getter "hhmm"
  moment()
    .constructor
    .prototype
    .__defineGetter__('hhmm', function() {
      let hour = this.hour();
      if (hour < startHour)
        hour += 24;
      const hh = `${hour < 10 ? '0':''}${hour}`;
      return `${hh}:${this.format('mm')}`;
    });

  // enhance moment() to handle the parameter with "HH:mm"(HH >= 25) format String
  const _moment = moment;

  window.moment = function() {
    if (arguments.length === 2 && arguments[1]=== 'HH:mm') {
      const matches = /^([0-9]{2}):([0-9]{2})$/.exec(arguments[0]);
      if (matches) {
        const h = parseInt(matches[1]);
        if (24 < h && h < 24 + startHour) {
          return _moment().add(1, 'day').hour(h-24).minute(parseInt(matches[2])).second(0);
        }
      }
    }
    return _moment(...[...arguments]);
  };

  window.hhmm = function(s) {
    return window.moment(s, 'HH:mm');
  };
}

できること

  • READMEのsamples にも書きましたが、以下のようなことができます。
const t0 = hhmm('00:00');
console.log(t0.hhmm); // "24:00"
const t1 = hhmm('24:00');
console.log(t1.hhmm); // "24:00"
const t2 =hhmm('21:45');
console.log(t2.hhmm); // "21:45"
const t3 = hhmm('05:21');
console.log(t3.hhmm); // "29:21"
const t4 = hhmm('28:15');
console.log(t4.hhmm); // "28:15"
const t5 = hhmm('21:00');
const t6 = hhmm('26:45');
console.log(t6.isAfter(t5));  // true
console.log(t5.isBefore(t6)); // true
console.log(t6.diff(t5, 'minutes')); // 345
console.log(t6.diff(t5, 'hours'));   // 5
console.log(t6.diff(t5, 'hours', true)); // 5.750271388888889 (or float value nearly 5.75 ) 
const t7 = hhmm('22:45');
const t8 = t7.add(4.5, 'hours');
console.log(t8.hhmm); // "27:15"

const t9 = t8.add(-20, 'minutes');
console.log(t9.hhmm); // "26:55"

以上です。30分ぐらいでざっくり書いたコードですので、見落としがあるかもしれません。
何かツッコミあれば下さい。

4
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4