2015-02-24 65 views

回答

14

更新時間面板每一秒,我們應該使用setInterval()功能。

要格式化日期,您需要的最佳方法是使用moment.js庫。該代碼大大縮短:

$(document).ready(function() { 
    var interval = setInterval(function() { 
     var momentNow = moment(); 
     $('#date-part').html(momentNow.format('YYYY MMMM DD') + ' ' 
          + momentNow.format('dddd') 
          .substring(0,3).toUpperCase()); 
     $('#time-part').html(momentNow.format('A hh:mm:ss')); 
    }, 100); 
}); 

Here is working fiddle

+0

我得到的時刻是沒有定義的錯誤。你能解釋爲什麼嗎? – 2017-03-16 06:53:46

+0

我修好了。一些JavaScript碰撞導致錯誤 – 2017-03-16 07:00:17

1

您可以在JavaScript中使用SetInterval,並在每1秒後運行它。 查找給出的示例

<!DOCTYPE html> 
<html> 
<body> 

<p>A script on this page starts this clock:</p> 
<p id="demo"></p> 
<p id="demonew"></p> 
<script> 
var today = new Date(); 
var dd = today.getDate(); 
var mm = today.getMonth()+1; //January is 0! 
var yyyy = today.getFullYear(); 
if(dd<10) { 
    dd='0'+dd 
} 

if(mm<10) { 
    mm='0'+mm 
} 

today = mm+'/'+dd+'/'+yyyy; 
document.getElementById("demonew").innerHTML = today; 
var myVar=setInterval(function(){myTimer()},1000); 

function myTimer() { 
    var d = new Date(); 
    document.getElementById("demo").innerHTML = d.toLocaleTimeString(); 
} 
</script> 

</body> 
</html> 
1
You can use : 
    <script> 
    var mydate=new Date() 
    var year=mydate.getYear() 

if (year < 1000) 
    year+=1900 

var day=mydate.getDay() // Current Day of week - 2 
var month=mydate.getMonth() // Current Month 2 
var daym=mydate.getDate() // Current Date -24 
var h=mydate.getHours(); //Hours 
var m=mydate.getMinutes();//Minutes 
var s=mydate.getSeconds();//Seconds 
m = checkTime(m); 
s = checkTime(s); 

function checkTime(i) { 
    if (i<10) {i = "0" + i}; // add zero in front of numbers < 10 
return i; 
} 

取2個陣列

var dayarray=new Array("Sunday","Monday","Tuesday","Wednesday","Thursday", 
         "Friday","Saturday") 
var montharray=new Array("January","February","March","April","May","June", 
         "July","August","September","October","November","December") 

    document.getElementById('txt').innerHTML =h+":"+m+":"+s+" "+dayarray[day]+", "+montharray[month]+" "+daym+", "+year; 

var t = setTimeout(function(){startTime()},500); 
    //This will update time 


</script> 
    <body onload="startTime()"> 

    <div id="txt"></div> 

    </body>