0
1

More than 3 years have passed since last update.

【JavaScript】Moment Timezone

Posted at

Moment Timezoneは日付の操作などの機能を提供するライブラリです。
早速インストールして使っていきます。

npm i --save moment-timezone

基本的な使い方

moment()メソッドを使います。
引数なしの場合、現在時刻が返されます。

const now = moment()
console.log(now)//2020-03-01T17:22:39+09:00

色々な形式で取得することが可能です。


const now = moment().toDate() //Date型を返す。Sun Mar 01 2020 17:28:10 GMT+0900 (GMT+09:00) {}
const now = moment().unix() //unixのタイムスタンプを返す。1583051420
const now = moment().toDate() // ISO 形式 (ISO 8601) の文字列を返す。2020-03-01T08:31:45.639Z

日時の加減

addメソッドとsubstractメソッドを使用します。
第一引数には加減する値、第二引数には単位を渡します。

moment(now).add(10,"year").format() //2030-03-01T17:31:45+09:00
moment(now).subtract(10,"year").format() //2010-03-01T17:31:45+09:00

第二引数に渡す単位は省略形でも構いません。
年 「'year' or 'y'」
月 「'month' or 'M'」
週 「'week' or 'w'」
日 「'day' or 'd'」
時 「'hour' or 'h'」
分 「'minutes' or 'm'」
秒 「'second' or 's'」

日時の始まり・終わり

startOfメソッドとendOfメソッドで指定した単位の始まりと終わりを取得できます。

moment(now).startOf("year").format() //2020-01-01T00:00:00+09:00
moment(now).endOf("year").format() //2020-12-31T23:59:59+09:00

コピー

元の日時を変更させたくない場合、cloneメソッド でコピーを作成します。

  const now2 = moment('1900-01-01 01:01:01')
  const clone = now2.clone()
  clone.add(1000,'year').format()// 2900-01-01T01:01:01+09:00
  clone.format()// 2900-01-01T01:01:01+09:00
  now2.format()// 1900-01-01T01:01:01+09:00

差分

diffメソッドで渡したデータとの差分を返します。
第二引数には差分を出す単位を渡します。
何も渡さない場合はミリ秒が返されます。

  const toData = ('2000-01-01 00:00:00')
  const fromData = ('2020-01-01 00:00:00')
  moment(fromData).diff(toData)// 631152000000
  moment(fromData).diff((toData),'year')// 20

比較

渡した日時と比較をし、真偽値が返されます。
isAfterメソッドでaはbより後かの比較
isBeforeメソッドでaはbより前かの比較
isAfterメソッドでaはbと同じもしくは後かの比較
isBeforeメソッドでaはbと同じもしくは前かの比較
isBetweenメソッドでaはbの範囲内かの比較

  a.isAfter(b)// false
  b.isAfter(a)// true
  a.isBefore(b)// true
  b.isBefore(a)// false
  a.isSameOrAfter(b)// false
  b.isSameOrAfter(a)// true
  a.isSameOrBefore(b)// true
  b.isSameOrBefore(a)// false
  a.isBetween(b)// false
  b.isBetween(a)// true

format

formatメソッドで日時の表示形式を変更することができます。

  c.format('M') //01
  c.format('MM') //01
  c.format('MMM') //Jan
  c.format('MMMM') //January

  c.format('d') //3
  c.format('dd') //we
  c.format('ddd') //wed
  c.format('dddd') //wednesday

localeメソッドで日本を指定すると日本語形式で返されます。


moment.locale('ja')
0
1
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
0
1