我有一个脚本,打印当前的日期和时间在JavaScript,但日期总是错误的。代码如下:
var currentdate = new Date();
var datetime = "Last Sync: " + currentdate.getDay() + "/" + currentdate.getMonth()
+ "/" + currentdate.getFullYear() + " @ "
+ currentdate.getHours() + ":"
+ currentdate.getMinutes() + ":" + currentdate.getSeconds();
它应该打印18/04/2012 15:07:33和打印3/3/2012 15:07:33
看看这个也许会对你有用
<script language="JavaScript">
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")
function getthedate(){
var mydate=new Date()
var year=mydate.getYear()
if (year < 1000)
year+=1900
var day=mydate.getDay()
var month=mydate.getMonth()
var daym=mydate.getDate()
if (daym<10)
daym="0"+daym
var hours=mydate.getHours()
var minutes=mydate.getMinutes()
var seconds=mydate.getSeconds()
var dn="AM"
if (hours>=12)
dn="PM"
if (hours>12){
hours=hours-12
}
if (hours==0)
hours=12
if (minutes<=9)
minutes="0"+minutes
if (seconds<=9)
seconds="0"+seconds
//change font size here
var cdate="<small><font color='000000' face='Arial'><b>"+dayarray[day]+",
"+montharray[month]+" "+daym+", "+year+" "+hours+":"
+minutes+":"+seconds+" "+dn
+"</b></font></small>"
if (document.all)
document.all.clock.innerHTML=cdate
else if (document.getElementById)
document.getElementById("clock").innerHTML=cdate
else
document.write(cdate)
}
if (!document.all&&!document.getElementById)
getthedate()
function goforit(){
if (document.all||document.getElementById)
setInterval("getthedate()",1000)
}
</script>
enter code here
<span id="clock"></span>
. getmonth()返回一个从零开始的数字,所以为了得到正确的月份,你需要加1,所以在五月调用. getmonth()将返回4而不是5。
因此,在代码中,我们可以使用currentdate.getMonth()+1来输出正确的值。此外:
.getDate()返回月份的日期<-这是你想要的
.getDay()是Date对象的一个单独方法,它将返回一个整数,表示一周中的当前日期(0-6)0 ==星期日等
所以你的代码应该是这样的:
var currentdate = new Date();
var datetime = "Last Sync: " + currentdate.getDate() + "/"
+ (currentdate.getMonth()+1) + "/"
+ currentdate.getFullYear() + " @ "
+ currentdate.getHours() + ":"
+ currentdate.getMinutes() + ":"
+ currentdate.getSeconds();
JavaScript Date实例继承自Date.prototype。您可以修改构造函数的原型对象,以影响JavaScript Date实例继承的属性和方法
您可以使用Date原型对象创建一个新方法,该方法将返回今天的日期和时间。这些新方法或属性将由Date对象的所有实例继承,因此在需要重用此功能时特别有用。
// For todays date;
Date.prototype.today = function () {
return ((this.getDate() < 10)?"0":"") + this.getDate() +"/"+(((this.getMonth()+1) < 10)?"0":"") + (this.getMonth()+1) +"/"+ this.getFullYear();
}
// For the time now
Date.prototype.timeNow = function () {
return ((this.getHours() < 10)?"0":"") + this.getHours() +":"+ ((this.getMinutes() < 10)?"0":"") + this.getMinutes() +":"+ ((this.getSeconds() < 10)?"0":"") + this.getSeconds();
}
然后,您可以通过执行以下操作简单地检索日期和时间:
var newDate = new Date();
var datetime = "LastSync: " + newDate.today() + " @ " + newDate.timeNow();
或者将该方法调用为内联,这样它就是-
var datetime = "LastSync: " + new Date().today() + " @ " + new Date().timeNow();