LoginSignup
4
1

More than 5 years have passed since last update.

"12:30:50"をISO formatに変換

Last updated at Posted at 2016-09-19

moment.js12:30:50をそのまま渡すと、validではないmomentオブジェクトになる

Deprecation warning: value provided is not in a recognized ISO format. moment construction falls back to js Date(), which is not reliable across all browsers and versions. Non ISO date formats are discouraged and will be removed in an upcoming major release. Please refer to http://momentjs.com/guides/#/warnings/js-date/ for more info.

こんなDeprecated Warningがブラウザコンソールに出る

time = moment().format('H:mm:ss') //=> "12:30:50"
moment(time).isValid() // => false

「12:30:50 PM の44分32秒後」をmoment.js使って知りたくても

moment(time).add(44, 'minutes').add(32, 'seconds').format('H:mm:ss') 
//=> 'invalid date'

となってしまう。

なのでISO formatに変換する必要がある

// @flow
const getISOSformat = (str: string) => string {
  if (!/^(?:0?|[1-2])\d:(?:0?|[1-5])\d:(?:0?|[1-5])\d$/.test(str)) throw new Error('not H:mm:ss')

  const [h, m, s]  = str.split(':')
  const d =  new Date()
  d.setHours(h)
  d.setMinutes(m)
  d.setSeconds(s)
  return d.toISOString()
}
moment(getISOSformat("19:54:57")).add(6, 'minutes').format('H:mm:ss')
// => 8:37:31

2016/10/12 の42日後」とかもmoment.js使って知りたいときは同じやり方でいけると思う

4
1
3

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
1