0

-実現したいこと-

時間と分のみを設定してあとは現在時刻を表示させるようにしたいです。

= latest access: 2022/9/25 23:25

<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>テンプレート</title>
<link href="../../_common/images/favicon.ico" rel="shortcut icon">
<link href="https://fonts.googleapis.com/css?family=M+PLUS+1p:400,500" rel="stylesheet">
<link href="../../_common/css/style.css" rel="stylesheet">
</head>
<body>
<header>
<div class="container">
<h1>タイトル</h1>
<h2>サブタイトル</h2>
</div><!-- /.container -->
</header>
<main>
<div class="container">
<section>

<p>latest access: <span id="time"></span></p>

</section>
</div><!-- /.container -->
</main>
<footer>
<div class="container">
<p>JavaScript Samples</p>
</div><!-- /.container -->
</footer>

<script>

    const now = new Date();
    const year = now. getFullYear();
    const month = now.getMonth();
    const date = now.getDate();
    const hour = now.setHours(23);
    const min = now.setMinutes(25);



let ampm = '';

if (hour < 12) {
 ampm = 'a.m.';
} else {
    ampm = 'p.m.';
}

const output = `${year}/${month + 1}/${date}  ${hour % 12}:${min}${ampm}`;
    document.getElementById('time').textContent = output;



</script>
</body>
</html>

1 件の回答 1

4

setHoursgetHours の機能を混同しているようです。setMinutesgetMinutes も同様。

setHoursは時間を設定します。返り値は日付/時刻になります。
getHoursは日付/時刻から時間を数値として取得します。

const now = new Date();
now.setHours(23);
now.setMinutes(25);
const year = now.getFullYear();
const month = now.getMonth();
const date = now.getDate();
const hour = now.getHours();
const min = now.getMinutes();

let ampm = "";

if (hour < 12) {
  ampm = "a.m.";
} else {
  ampm = "p.m.";
}

const output = `${year}/${month + 1}/${date}  ${hour % 12}:${min}${ampm}`;
document.getElementById("time").textContent = output;
<header>
  <div class="container">
    <h1>タイトル</h1>
    <h2>サブタイトル</h2>
  </div><!-- /.container -->
</header>
<main>
  <div class="container">
    <section>

      <p>latest access: <span id="time"></span></p>

    </section>
  </div><!-- /.container -->
</main>
<footer>
  <div class="container">
    <p>JavaScript Samples</p>
  </div><!-- /.container -->
</footer>

1
  • ありがとうございます。ご指摘の通り、setHoursとsetMinutesの役割を正しく理解できていませんでした。
    – Iori_ss67
    2022年9月25日 11:55

この質問に回答するには、ログインする必要があります。

求めていた回答ではありませんか? のタグが付いた他の質問を参照する。