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,14,日付を取得・表示,Date,

Posted at

14,JavaScriptで日付を取得・表示などをするための方法

JavaScript(ジャバスクリプト)のDateオブジェクトを使って、
今日の日時や曜日などを取得・表示してみましょう!
基本が分かったら、明日の今の日時を表示したり、
ある日付までのカウントダウン日を表示させてみる方法を紹介しています。

const today = new Date();
days = ["日", "月", "火", "水", "木", "金","土"]

console.log(today.getFullYear());
console.log(today.getMonth() + 1);
console.log(today.getDate());
console.log(today.getHours());
console.log(today.getMinutes());
console.log(today.getSeconds());
console.log(days[today.getDay()]);

月は0が1月 1が2月 になるので+1すること
曜日に関しては01234の数値になるので
配列を作っておく

      days = ["日", "月", "火", "水", "木", "金","土"]

let outputtext = "今は";
outputtext += "「" + today.getFullYear() + "年";
outputtext += (today.getMonth() + 1) + "月";
outputtext += today.getDate() + "日";
outputtext += today.getHours() + "時";
outputtext += today.getMinutes() + "分";
outputtext += today.getSeconds() + "秒";
outputtext += "(" + days[today.getDay()] + ")";
outputtext += "」です";

document.getElementById("date").textContent = outputtext;

今は「2020年12月14日0時40分47秒(月)」です

const today = new Date();
      days = ["日", "月", "火", "水", "木", "金","土"]

function outputDate(date) {
  let outputtext = "「" + date.getFullYear() + "年";
  outputtext += (date.getMonth() + 1) + "月";
  outputtext += date.getDate() + "日";
  outputtext += date.getHours() + "時";
  outputtext += date.getMinutes() + "分";
  outputtext += date.getSeconds() + "秒";
  outputtext += "(" + days[date.getDay()] + ")";
  outputtext += "」です";
  return outputtext;
}
document.getElementById("date").textContent = "今は" + outputDate(today);

today.setDate(today.getDate() + 1);
document.getElementById("tomorrow").textContent = "明日の今は" + outputDate(today);

今は「2020年12月14日0時54分29秒(月)」です
明日の今は「2020年12月15日0時54分29秒(火)」です

today.setDateはまた新たに日を取得する

const targetDate = new Date(2021, 7 -1, 23);
document.getElementById("countDown").textContent = "オリンピックまであと" + Math.ceil((targetDate - today) / (1000 * 60 * 60 * 24)) + "日";

オリンピックまであと221日

new Date(2021, 7 -1, 23)
この指定した日までのカウントダウン

Math.ceil端数切り上げ

0
0
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
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?