Two JavaScript Ways to Display the Current Time in Firefox Correctly
There are plenty of JavaScript snippets online for showing the current date and time, but many of them are not fully reliable in Firefox. A common reason is the old year-formatting problem, where a year like 2009 may end up being displayed as 109.
If you need a simple clock script that works properly in Firefox, the following two approaches can be used.
Method 1
This version writes the current local date and time directly into a DIV, then refreshes it once per second. It also appends the weekday.
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>兼容FireFox的当前时间的JS脚本</title>
</head>
<body>
<DIV id=time>当前时间
<SCRIPT>document.getElementById('time').innerHTML=new Date().toLocaleString()+' 星期'+'日一二三四五六'.charAt(new Date().getDay());setInterval("document.getElementById('time').innerHTML=new Date().toLocaleString()+' 星期'+'日一二三四五六'.charAt(new Date().getDay());",1000);</SCRIPT>
</DIV>
</body>
</html>
This approach is compact and straightforward. It uses toLocaleString() for the current date and time, then combines it with the weekday calculated from getDay().
Method 2
The second version builds the date and time manually. It extracts the year, month, day, hour, minute, and second separately, formats the values, and then outputs a full string including the weekday.
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>兼容FireFox的当前时间的JS脚本</title>
<script type="text/javascript">
<!--
function startTime()
{
var today=new Date()
var years=today.getFullYear();
var months=today.getMonth();
var d=today.getDate()
var h=today.getHours()
var m=today.getMinutes()
var s=today.getSeconds()
// add a zero in front of numbers<10
months=months+1
months=checkTime(months)
d=checkTime(d)
m=checkTime(m)
s=checkTime(s)
var weekday=new Array(7)
weekday[0]="星期日"
weekday[1]="星期一"
weekday[2]="星期二"
weekday[3]="星期三"
weekday[4]="星期四"
weekday[5]="星期五"
weekday[6]="星期六"
var w=weekday[today.getDay()]
document.getElementById('ShowTime').innerHTML=years+"年"+months+"月"+d+"日 "+w+" "+h+":"+m+":"+s;
t=setTimeout('startTime()',500)
}
function checkTime(i)
{
if (i<10)
{i="0" + i}
return I
}
-->
</script>
</head>
<body>
<body onload="startTime()">
<div id="ShowTime"></div>
</body>
</html>
Compared with the first method, this one gives you more control over the output format. It explicitly uses getFullYear() and constructs the full display string step by step, which helps avoid the kind of year display issue that can appear in older scripts.
If the goal is simply to show the current time on a page and keep it updating in Firefox, either of these two examples can serve as a practical starting point.