前置き
基礎編に続き応用編です。
2つの日時の差分を出していきます🕰
基礎編はこちら
【Nuxt.js】dayjs導入編:リアルタイムな日時を表示してみよう
https://qiita.com/aLiz/items/8de5727e274f1a9a1efe
復習
・dayjs() =パース
・format() =表示形式の指定
<p v-text="$dayjs().format('dddd、MMMM D、YYYY h:mm A')" />
表示結果
Tuesday、February 4、2020 1:33 PM
dddd MMMM D ……長い!😒笑
省略したい場合はLLLLで同じ表記に。
この辺りも基礎編で解説済みです。
https://github.com/iamkun/dayjs/blob/dev/docs/en/I18n.md
・locale('ja')を指定で日本語表記
<p v-text="$dayjs().locale('ja').format('dddd、MMMM D、YYYY h:mm A')" />
表示結果
2020年2月4日 火曜日 13:33
❓ではこれは
※グローバルでlocale('ja')指定済み
<p v-text="$dayjs('February 4, 2020').add(1, 'year').format('YYYY')" />
表示結果
2021
ですね💡
dayjsで2020年2月4日をパース(解析)
そこに1年追加し2021年2月4日とし
表示形式を年数字のみにしているためですね🧸
カウントダウン
では基礎編を踏まえて
2つの日時の差分を出しましょう!
あと何ヶ月、とかあと何日!
差分はditt()を使用します。
<p v-text="$dayjs('2020-02-04').diff('2020-01-01')" />
結果はミリ秒で表示
2937600000
ミリ秒で見てもパッとしないので
月の差分を見てみましょう〜🌟🌝
<p v-text="$dayjs('2020-02-04').diff('2020-01-01', 'month') + '月'" />
結果は1ヶ月ですね。
diffの第二引数がformatのような役割です。
1月
日付
<p v-text="$dayjs('2020-02-04').diff('2020-02-01', 'day') + '日'" />
結果
3日
時間
<p v-text="$dayjs('2020-02-04T12:30:00').diff('2020-02-04T10:30:00', 'h') + '時間'" />
結果
2時間
基礎が分かれば簡単ですね🤗
記事が公開したときにわかる様に、
note・Twitterフォローをお願いします😀
https://twitter.com/aLizlab