我有一个脚本,打印当前的日期和时间在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


当前回答

您需要使用getDate()来获取日期部分。getDay()函数返回日期(Sunday = 0, Monday = 1…),getMonth()返回一个基于0的索引,因此需要将其增加1。

 var currentdate = new Date(); 

 var datetime = "Last Sync: " + currentdate.getDate() + "/"+  (parseInt(currentdate.getMonth())    + 1)
   + "/" + currentdate.getFullYear() + " @ "  
   + currentdate.getHours() + ":"  
   + currentdate.getMinutes() + ":" + currentdate.getSeconds(); 

其他回答

getDay()获取星期几。3号是星期三。你需要getDate(),它会返回18。

同样,getMonth()从0开始,你需要加1来得到4(四月)。

演示:http://jsfiddle.net/4zVxp/

来获得你应该使用的时间和日期

    new Date().toLocaleString();

>> "09/08/2014, 2:35:56 AM"

只得到你应该使用的日期

    new Date().toLocaleDateString();

>> "09/08/2014"

只得到你该用的时间

    new Date().toLocaleTimeString();

>> "2:35:56 AM"

或者如果你只是想要格式为hh:mm而不是AM/PM的美式英语时间

    new Date().toLocaleTimeString('en-US', { hour12: false, 
                                             hour: "numeric", 
                                             minute: "numeric"});
>> "02:35"

或英式英语

    new Date().toLocaleTimeString('en-GB', { hour: "numeric", 
                                             minute: "numeric"});

>> "02:35"

点击这里阅读更多。

您需要使用getDate()来获取日期部分。getDay()函数返回日期(Sunday = 0, Monday = 1…),getMonth()返回一个基于0的索引,因此需要将其增加1。

 var currentdate = new Date(); 

 var datetime = "Last Sync: " + currentdate.getDate() + "/"+  (parseInt(currentdate.getMonth())    + 1)
   + "/" + currentdate.getFullYear() + " @ "  
   + currentdate.getHours() + ":"  
   + currentdate.getMinutes() + ":" + currentdate.getSeconds(); 

<p id="DateTimeBox">点击按钮显示日期和时间 <按钮onclick = " ShowDate ();">显示日期</button> . < >脚本 函数ShowDate() { . getelementbyid(“DateTimeBox”)。innerHTML = Date(); } > < /脚本

我善意的回答是使用这个小小的JS: https://github.com/rhroyston/clock-js

clock.now   --> 1462248501241
clock.time  --> 11:08 PM
clock.weekday   --> monday
clock.day   --> 2
clock.month --> may
clock.year  --> 2016
clock.since(1462245888784)  --> 44 minutes
clock.until(1462255888784)  --> 2 hours
clock.what.time(1462245888784)  --> 10:24 PM
clock.what.weekday(1461968554458)   --> friday
clock.what.day('14622458887 84')    --> 2
clock.what.month(1461968554458) --> april
clock.what.year('1461968554458')    --> 2016
clock.what.time()   --> 11:11 PM
clock.what.weekday('14619685abcd')  -->     clock.js error : expected unix timestamp as argument
clock.unit.seconds  --> 1000
clock.unit.minutes  --> 60000
clock.unit.hours    --> 3600000
clock.unit.days --> 86400000
clock.unit.weeks    --> 604800000
clock.unit.months   --> 2628002880
clock.unit.years    --> 31536000000