javascript 今年から経過した日数を取得する
- 作成日 2022.09.19
- javascript
- javascript

javascriptで、今年から経過した日数を取得するサンプルコードを記述してます。
環境
- OS windows10 pro 64bit
- Apache 2.4.43
- ブラウザ chrome 105.0.5195.102
今年から経過した日数を取得
今年から経過した日数を取得するには、元旦からの経過時間を計算することで取得できます。
const y = `${new Date().getFullYear()}/1/1`
const nt = new Date(y).getTime();
const t = Date.now() - nt;
console.log( Math.floor( t / 1000 / 60 / 60 / 24 ) + 1 ) // +1 は 1月1日を加算している
実行結果(実行日付は5/14)

サンプルコード
以下は、
「実行」ボタンをクリックすると、現在日付を取得して経過日数を取得して表示する
サンプルコードとなります。
※cssには「tailwind」を使用してます。関数はアロー関数を使用してます。
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8" />
<title>mebeeサンプル</title>
<link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet" />
</head>
<script>
window.onload = () => {
// クリックイベントを登録
btn.onclick = () => {
const y = `${new Date().getFullYear()}/1/1`
const nt = new Date(y).getTime();
const t = Date.now() - nt;
result.textContent = `${Math.floor(t / 1000 / 60 / 60 / 24) + 1}日経過`
}; // document.getElementById('btn');を省略
};
</script>
<body>
<div class="container mx-auto my-56 w-56 px-4">
<div class="flex justify-center">
<p id="result" class="bg-green-500 text-white py-2 px-4 rounded-full mb-3 mt-4">
実行結果
</p>
</div>
<div class="flex justify-center">
<button id="btn" type="button"
class="mt-5 bg-transparent border border-red-500 hover:border-red-300 text-red-500 hover:text-red-300 font-bold py-2 px-4 rounded-full">
実行
</button>
</div>
</div>
</body>
</html>
経過日数が表示されていることが確認できます。

-
前の記事
SQL Server 右から指定した文字数を抽出する 2022.09.19
-
次の記事
sakuraエディタ ブックマークするショートカットキー 2022.09.19
コメントを書く