@yam33 (邦彦 山中)

Are you sure you want to delete the question?

If your question is resolved, you may close it.

Leaving a resolved question undeleted may help others!

We hope you find it useful!

unixtimeを変換して表示したい(HTML/javascript)

解決したいこと

unixtimeで保存されているデータ(例:1628220346)をHTML(javascript)で年月日として表示したい。
また、その日付の3ヶ月後の日付も表示したい。

CGIのデータ表示部分にunixtimeで保存されているデータは読み込み出来るので、それを変換表示できればと考えております。

例)
1628220346 ---> 2021年08月06日 2021年11月06日


### 自分で試したこと
どなたか教えて下さい
0 likes

3Answer

変換部分のみ紹介します。Dateオブジェクトを使用します。

const unixtime = 1628220346;
const date = new Date(unixtime * 1000); // ミリ秒
console.log(date.toLocaleDateString('ja-JP', { year: 'numeric', month: 'long', day: 'numeric' }));
// > 2021年8月6日

date.setMonth(date.getMonth() + 3); // +3ヶ月
console.log(date.toLocaleDateString('ja-JP', { year: 'numeric', month: 'long', day: 'numeric' }));
// > 2021年11月6日

// 変換する日付が多い場合は下のほうがパフォーマンスが良い
const formatter = new Intl.DateTimeFormat('ja-JP', { year: 'numeric', month: 'long', day: 'numeric' });
console.log(formatter.format(date));
// > 2021年11月6日

0Like

Comments

  1. @yam33

    Questioner

    回答ありがとうございます!
    素人ながら下記の感じでとりあえず表示出来ました。

    <script>
    const unixtime = 1628220346;
    const date = new Date(unixtime * 1000); // ミリ秒
    document.write('<p>掲載日:');
    document.write(date.toLocaleDateString('ja-JP', { year: 'numeric', month: 'long', day: 'numeric' }));
    document.write('</p>');
    // > 2021年8月6日

    date.setMonth(date.getMonth() + 3); // +3ヶ月
    document.write('<p>次回更新日:');
    document.write(date.toLocaleDateString('ja-JP', { year: 'numeric', month: 'long', day: 'numeric' }));
    document.write('</p>');
    // > 2021年11月6日
    </script>
  2. @yam33

    Questioner

    もう少しスマートに下記のように表示出来ますでしょうか?

    <table border="1">
    <tr>
    <td>掲載日</td><td>2021年8月6日</td><td>次回更新日</td><td>2021年11月6日</td>
    </tr>
    </table>

また、その日付の3ヶ月後の日付も表示したい。

3ヶ月後の定義(主に月末付近での処理)はどのように考えていらっしゃいますか?

例えば2021年11月30日の3か月後であれば、単純に2022年03月02日でいいのか、それとも目標月の末日で丸めて2022年02月28日とするのか。

0Like

Comments

  1. @yam33

    Questioner

    ご回答ありがとうございます。
    末処理の件、ご指摘ありがとうございます。
    単純に2022年03月02日で大丈夫です。
    宜しくお願いします。

データ形式がどういうものか不明ですが関数にしてテーブルを作る例を載せます。(あまりスマートではないです。)

<table border=1><tbody id=tbody></tbody></table>
<script>
const formatter = new Intl.DateTimeFormat('ja-JP', { year: 'numeric', month: 'long', day: 'numeric' });
const tbody = document.getElementById('tbody');

function insertDateRow(unixtime) {
  const date = new Date(unixtime * 1000);
  const publishDate = formatter.format(date);
  date.setMonth(date.getMonth() + 3);
  const updateDate = formatter.format(date);
  tbody.insertAdjacentHTML('beforeend', `<tr><td>掲載日</td><td>${publishDate}</td><td>次回更新日</td><td>${updateDate}</td></tr>`);
}

// insertDateRow(1628220346);
</script>
0Like

Comments

  1. @yam33

    Questioner

    ご回答ありがとうございます。
    希望の表示が出来ました!
    大変助かりました。
    この度はありがとうございました。

Your answer might help someone💌