LoginSignup
16
17

More than 3 years have passed since last update.

Vue.js で Moment.js を使ってお手軽に日付フォーマットする

Posted at

 Vue.js のフィルタでフォーマット

Moment.js を使ったフィルタを用意すると以下のようにお手軽に日付のフォーマットが可能です。

<template>
  <h1>{{ new Date() | moment('LTS') }}</h1>
</template>

image.png

JavaScript の日付処理は罠が多い

  • Date#getYearで1900年からの経過年数が返る
  • Date#getMonthで 0 ~ 11 が返る。

JavaScript の日付処理ライブラリである Moment.js を使えばそういった罠を回避し、お手軽に JavaScript の日付を扱うことができます。

現在、Github のスターは 40000 を超え JavaScript の日付処理ライブラリでは最もメジャーなものの一つです。
image.png

フィルタの作り方

サンプルプロジェクトを作成します。
既存のプロジェクトに組み込む場合、ここは必要ありません。

# Vue CLI のインストール ※すでにインストール済みなら必要なし
$ npm install -g @vue/cli

$ npm install -g @vue/cli
# yarn global add @vue/cli

$ cd 任意のディレクトリ

$ vue create moment-filter

$ cd moment-filter

Moment.js をインストールします。

# Moment.jsをインストールする
$ npm install moment --save 
# yarn add moment 

Moment.js を使ったフィルタを作成します。

import moment from "moment";

/* 中略 */

  filters: {
    /**
     * @param {Date} value    - Date オブジェクト
     * @param {string} format - 変換したいフォーマット
     */
    moment(value, format) {
      return moment(value).format(format);
    }
  }

上記で完成です。簡単。

テストの表示

テストデータを用意して試してみましょう。

data() {
    const formats = [
      "MMMM Do YYYY, h:mm:ss a",
      "dddd",
      "MMM Do YY",
      "YYYY [escaped] YYYY",
      "LTS"
    ];
    return {
      tests: new Array(formats.length)
        .fill(new Date())
        .map((date, i) => ({ date, format: formats[i] }))
    };
  }

今回はとりあえず以下のように並べて表示してみます。

<template>
  <div id="app">
    <h2 v-for="({date, format}, index) in tests" :key="index">{{date | moment(format)}}</h2>
  </div>
</template>

ローカルサーバーを立ち上げます。

$ npm run serve
# yarn serve

image.png

フォーマットされた日付が表示できました。

今回作成したコンポーネントの全体は以下のとおりです。

./src/App.vue
<template>
  <div id="app">
    <h2 v-for="({date, format}, index) in tests" :key="index">{{date | moment(format)}}</h2>
  </div>
</template>

<script>
import moment from "moment";

export default {
  name: "app",
  data() {
    const formats = [
      "MMMM Do YYYY, h:mm:ss a",
      "dddd",
      "MMM Do YY",
      "YYYY [escaped] YYYY",
      "LTS"
    ];
    return {
      tests: new Array(formats.length)
        .fill(new Date())
        .map((date, i) => ({ date, format: formats[i] }))
    };
  },
  filters: {
    moment(value, format) {
      return moment(value).format(format);
    }
  }
};
</script>

<style>
#app {
  font-family: "Avenir", Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>
16
17
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
16
17