본문 바로가기

Javascript

ChatGPT활용해 JS에 현재 시간 넣는 방법

튜터의 ChatGPT

<div class="greeting">
      <h1>Hello, My name!</h1>
      <h1 id="current-time"></h1>
</div>

<script>
    // 시간 chatgpt
    function displayCurrentTime() {
      var currentTime = new Date();
      var hours = currentTime.getHours();
      var minutes = currentTime.getMinutes();
      var seconds = currentTime.getSeconds();

      // Add leading zeros to minutes and seconds if they are less than 10
      minutes = (minutes < 10 ? "0" : "") + minutes;
      seconds = (seconds < 10 ? "0" : "") + seconds;

      // Determine if it's AM or PM
      var meridiem = hours >= 12 ? "PM" : "AM";

      // Convert to 12-hour format
      hours = hours % 12;
      hours = hours ? hours : 12;

      // Display the time in HH:MM:SS format
      var timeString = hours + ":" + minutes + ":" + seconds + " " + meridiem;

      // Display the time in an element with id "current-time"
      document.getElementById("current-time").innerHTML = timeString;
    }

    // Call the displayCurrentTime function every second to update the time
    setInterval(displayCurrentTime, 1000);
  
  </script>