Development Tip

HH : MM : SS 형식으로 JavaScript에서 현재 시간을 표시하는 방법은 무엇입니까?

yourdevel 2020. 10. 17. 12:29
반응형

HH : MM : SS 형식으로 JavaScript에서 현재 시간을 표시하는 방법은 무엇입니까?


HH : MM : SS이 형식으로 시간을 설정하는 방법을 알려주시겠습니까? div에서 설정하고 싶습니다.


function checkTime(i) {
  if (i < 10) {
    i = "0" + i;
  }
  return i;
}

function startTime() {
  var today = new Date();
  var h = today.getHours();
  var m = today.getMinutes();
  var s = today.getSeconds();
  // add a zero in front of numbers<10
  m = checkTime(m);
  s = checkTime(s);
  document.getElementById('time').innerHTML = h + ":" + m + ":" + s;
  t = setTimeout(function() {
    startTime()
  }, 500);
}
startTime();
<div id="time"></div>

JavaScript 만 사용하는 데모

최신 정보

Updated Demo

(function () {
    function checkTime(i) {
        return (i < 10) ? "0" + i : i;
    }

    function startTime() {
        var today = new Date(),
            h = checkTime(today.getHours()),
            m = checkTime(today.getMinutes()),
            s = checkTime(today.getSeconds());
        document.getElementById('time').innerHTML = h + ":" + m + ":" + s;
        t = setTimeout(function () {
            startTime()
        }, 500);
    }
    startTime();
})();

기본 기능을 사용할 수 있습니다 Date.toLocaleTimeString().

var d = new Date();
var n = d.toLocaleTimeString();

예를 들어 다음과 같이 표시됩니다.

"11:33:01"

http://www.w3schools.com/jsref/jsref_tolocaletimestring.asp 에서 찾았습니다 .

var d = new Date();
var n = d.toLocaleTimeString();
alert("The time is: \n"+n);


에서이 작업을 수행 할 수 있습니다 Javascript.

var time = new Date();
console.log(time.getHours() + ":" + time.getMinutes() + ":" + time.getSeconds());

현재 그것은 반환합니다 15:5:18. 값 중 하나라도 10보다 작 으면 두 자리가 아닌 한 자리 만 사용하여 표시됩니다.

JSFiddle 에서 확인하십시오.

업데이트 :
접두사가 0 인 경우 try

var time = new Date();
console.log(
    ("0" + time.getHours()).slice(-2)   + ":" + 
    ("0" + time.getMinutes()).slice(-2) + ":" + 
    ("0" + time.getSeconds()).slice(-2));

moment.js사용 하여 이를 수행 할 수 있습니다 .

var now = new moment();
console.log(now.format("HH:mm:ss"));

출력 :

16:30:03

new Date().toTimeString().slice(0,8)

toLocaleTimeString ()은 9:00:00 AM.


This code will output current time in HH:MM:SS format in console, it takes into account GMT timezones.

var currentTime = Date.now()
var GMT = -(new Date()).getTimezoneOffset()/60;
var totalSeconds = Math.floor(currentTime/1000);
seconds = ('0' + totalSeconds % 60).slice(-2);
var totalMinutes = Math.floor(totalSeconds/60);
minutes = ('0' + totalMinutes % 60).slice(-2);
var totalHours = Math.floor(totalMinutes/60);
hours = ('0' + (totalHours+GMT) % 24).slice(-2);
var timeDisplay = hours + ":" + minutes + ":" + seconds;
console.log(timeDisplay);
//Output is: 11:16:55

function realtime() {
  
  let time = moment().format('h:mm:ss a');
  document.getElementById('time').innerHTML = time;
  
  setInterval(() => {
    time = moment().format('h:mm:ss a');
    document.getElementById('time').innerHTML = time;
  }, 1000)
}

realtime();
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.1/moment.min.js"></script>

<div id="time"></div>

A very simple way using moment.js and setInterval.

setInterval(() => {
  moment().format('h:mm:ss a');
}, 1000)

Sample output

Using setInterval() set to 1000ms or 1 second, the output will refresh every 1 second.

3:25:50 pm

This is how I use this method on one of my side projects.

setInterval(() => {
  this.time = this.shared.time;
}, 1000)

Maybe you're wondering if using setInterval() would cause some performance issues.

Is setInterval CPU intensive?

I don't think setInterval is inherently going to cause you significant performance problems. I suspect the reputation may come from an earlier era, when CPUs were less powerful. ... - lonesomeday

No, setInterval is not CPU intensive in and of itself. If you have a lot of intervals running on very short cycles (or a very complex operation running on a moderately long interval), then that can easily become CPU intensive, depending upon exactly what your intervals are doing and how frequently they are doing it. ... - aroth

But in general, using setInterval really like a lot on your site may slow down things. 20 simultaneously running intervals with more or less heavy work will affect the show. And then again.. you really can mess up any part I guess that is not a problem of setInterval. ... - jAndy


This is an example of how to set time in a div(only_time) using javascript.

function date_time() {
    var date = new Date();
    var am_pm = "AM";
    var hour = date.getHours();
    if(hour>=12){
        am_pm = "PM";
    }
    if (hour == 0) {
        hour = 12;
    }
    if(hour>12){
        hour = hour - 12;
    }
    if(hour<10){
        hour = "0"+hour;
    }

    var minute = date.getMinutes();
    if (minute<10){
        minute = "0"+minute;
    }
    var sec = date.getSeconds();
    if(sec<10){
        sec = "0"+sec;
    }

    document.getElementById("time").innerHTML =  hour+":"+minute+":"+sec+" "+am_pm;
}
setInterval(date_time,500);
<per>
<div class="date" id="time"></div>
</per>

참고URL : https://stackoverflow.com/questions/18229022/how-to-show-current-time-in-javascript-in-the-format-hhmmss

반응형