0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

JavaScriptで Date を input 要素の日付(type="date") 用の文字列に変換する

Last updated at Posted at 2021-03-01

初めに

input 要素に今日の日付を既定値を設定する等の要件で JavaScript から設定できたら
何かと便利かなと思い、調査した結果の備忘録です。

検証ブラウザ

  • 動作OK
    • Chrome 88.0.4324.190(Official Build) (64 ビット)
    • Microsoft Edge バージョン 88.0.705.81 (公式ビルド) (64 ビット)
  • 動作NG
    • IE11

IE11 の場合、input type="date" がそもそも、テキスト表示になるため残念な感じです。
どうしてもIE11 で組む必要があるならば、jQuery UI の datepicker 等を利用して
フォーマットを合わせたら同じことはできそうです。

サンプルコード

<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
  </head>
  <body>
    <input type="date" id="date"/>
    <input type="datetime-local" id="datetime"/>
    <script>
      window.onload = function() {
        document.getElementById('date').value = dateString(new Date(),false);
        document.getElementById('datetime').value = dateString(new Date(),true);
      }

      function dateString(targetDate,isIncludeTime) {
        let year = targetDate.getFullYear();
        let month = ('0' + (targetDate.getMonth() + 1)).slice(-2);
        let date = ('0' + targetDate.getDate()).slice(-2);
        let result = year + '-' + month + '-' + date;

        if(isIncludeTime) {
          let hours = ('0' + targetDate.getHours()).slice(-2);
          let minutes = ('0' + targetDate.getMinutes()).slice(-2);
          result += 'T' + hours + ':' + minutes;
        }

        return result;
      }
    </script>
  </body>
</html>

解説

inputタグに対して値をセットする場合、value属性に対して値をセットすればよく
type="date"に指定した場合は、「yyyy-MM-dd」形式
type="datetime-local"に指定した場合は、「yyyy-MM-ddThh:mm」形式で与えれば上手く表示されます。

<input type="date" value="2020-04-20" />

image.png

なので、あとは JavaScript でセットしたい文字列を作って、セットするだけです。
toStringみたいな文字列関数で、フォーマットを引数に与え簡単に出力できるのかな?
と思いきや、便利な関数は用意されていないみたいなので(ないよね?)

年月日の取得

年月日の取得は月のみ注意が必要です。0~11を返却するので
3月に対して getMonth関数を呼び出すと2と返却されます。
そのため、日付用の文字列に直す場合、1足した値が必要です。

let today = new Date();
console.log(today);              //=> Mon Mar 01 2021 23:46:22 GMT+0900 (日本標準時)
console.log(today.getFullYear()) //=> 2021
console.log(today.getMonth())    //=> 2 (0~11)を返すので注意
console.log(today.getDate())     //=> 1

0埋め

年月日が取得できたので、あとはフォーマットに合わせて文字列にしたらOKなのですが
以下のように0埋めしない日付をvalueに指定しても画面に上手く表示されません。

<input type="date" value="2020-4-20" />

image.png

そのため、月、日に関しては 0埋めの2桁表示が必要です。
0埋は次のロジックで実現しています。

  • 文字列処理で先頭に0を付与する。単純に足し算で連結しています。
  • 文字列の末尾1桁を取得する。slice関数に負の数を指定することで末尾から取得できます。
('0' + 4) //=> '04'
('0' + 4).slice(-2) //=> '04'

('0' + 20) //=> '020'
('0' + 20).slice(-2) //=> '20'

関数 dateString

Dateオブジェクトを文字列に直す関数を作成しました。
引数として、文字列に直したいDateオブジェクト(targetDate)
時刻を含めるかどうかの真偽値(isIncludeTime)としています。

変数のネーミングセンスや英語力には自信がないので
おかしい部分もあるかもしれません。
英語を勉強しようかと思いながらも、基本1人でしかプログラミングしないので
その労力を惜しんでしまう悪い癖ですね。

0
0
2

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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?