LoginSignup
2
1

More than 5 years have passed since last update.

自分メモ:月や日の2桁表示方法

Last updated at Posted at 2017-03-29

phpだとsprintfを使うのが一般的?なんだろうけどJSの日付フォーマットに二桁表示させるものが用意されていない(ES6に追加されてるかどうかは知りませんwww)。
どうしても01月とか07日みたいな表示をしなきゃいけない場面に遭遇します。

そこで登場、みんな大好き?slice先生!

例えばgetMonthやgetDateで取得した値が一桁の場合、まずはそれに「0」を連結(この時点で型はstring)して強制的に2文字以上の文字列とし、slice先生に頑張ってもらって末尾から2文字になるようカットしてもらう!!(謎)

例)
値が1→01→Slice→01
値が20→020→Slice→20

参考として本日の西暦月日を出すコードは

sample.js
  var now = new Date();
  var today = now.getFullYear() + '' + ('0' + (now.getMonth() + 1)).slice(-2) + '' + ('0' + (now.getDate())).slice(-2) + '';
  console.info(today);

今日が2桁じゃない月や日の人はごめんねw

ちなみに
01や02をクオーテションでくくらない限り、型はnumberで、01+02という計算をすると「3」というnumberで返ってきます。

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