1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

moment.jsメモ

Last updated at Posted at 2016-11-16

moment.jsでfromNow()で26日前が「1ヶ月前」って返される件

26日前が1ヶ月前って表示されちゃう

// 25日前
console.log(moment().subtract(25, 'day').fromNow());

// 1ヶ月前
console.log(moment().subtract(26, 'day').fromNow());

relativeTimeThreshold()で閾値を変更することで解決する

// 閾値を変更
moment.relativeTimeThreshold('d', 31);

// 26日前
console.log(moment().subtract(26, 'day').fromNow());

...と思ったけど2ヶ月目以降やっぱずれはじめる

console.log('1',moment().add(-30*1+1,'day').format('YYYY/MM/DD')); // 2017/03/15 1ヶ月前 momentでは3/15から1ヶ月前になる
console.log('2',moment().add(-30*2+1,'day').format('YYYY/MM/DD')); // 2017/02/13 2ヶ月前 momentでは2/28から2ヶ月前になってしまう
console.log('3',moment().add(-30*3+1,'day').format('YYYY/MM/DD')); // 2017/01/14 3ヶ月前 momentでは1/29から3ヶ月前になってしまう

多言語環境下で注意したいformat変換

moment().format('YYYY/MM')ってすると普通は2016/01みたいな文字列がかえると思うが、ペルシア語環境とか(数値を文字で表す言語環境)だと۲۰۱۶۱۰みたいな文字列が返ってくる

moment.locale('fa');
moment().format('YYYY/MM'); // ۲۰۱۶۱۰

moment.localeData().preparse()を使うと期待した文字列に変換できる。

moment.locale('fa');
moment.localeData().preparse(moment().format('YYYY/MM')); // 2016/01

以下のような関数を定義しておくと良さそう

  /**
   * localeを考慮したDateオブジェクトの書式指定の文字列変換を行う
   *
   * ペルシャ語(fa)指定の状態で単純に momentObj.format('YYYY/MM') とすると
   * 「۲۰۱۶۱۰」のような値が返ってくる
   * 「2016/01」のような値が欲しい場合は、この文字列に対し
   *  moment.localeData().preparse('۲۰۱۶۱۰');
   * とすると期待どおりの値が取得できる
   *
   * @params {Date | moment} date
   * @params {string} format
   */
  function formatDateWithoutLocalization = function(date, format){
    date = moment.isMoment(date) ? date : moment(date);
    return moment.localeData().preparse(date.format(format));
  };

1月〜12月みたいな文字列を配列セットで得る方法

moment.months()を使う。

moment.months();
// -> ["1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月"]

moment.locale('en');
moment.months();
// -> ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]

moment.locale('fa');
moment.months();
// -> ["ژانویه", "فوریه", "مارس", "آوریل", "مه", "ژوئن", "ژوئیه", "اوت", "سپتامبر", "اکتبر", "نوامبر", "دسامبر]


1
3
2

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
1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?