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


当前回答

dt= new Date();
alert(dt.toISOString().substring(8,10) + "/" + 
dt.toISOString().substring(5,7)+ "/" + 
dt.toISOString().substring(0,4) + " " + 
dt.toTimeString().substring(0,8))

其他回答

function display_c(){   
    var refresh = 1000; // Refresh rate in milli seconds    
    mytime = setTimeout('display_ct()', refresh)    
}

function display_ct() {

    var strcount    
    var currentdate = new Date();

    document.getElementById('ct').innerHTML = currentdate.toDateString() + " " + currentdate.getHours() + ":" + currentdate.getMinutes() + ":" + currentdate.getSeconds();

    tt = display_c();   
}


id = 'ct'     // Replace in Your id

onload = "display_ct();"     // Type inside a Body Tag

如果有人在寻找功能

console.log(formatAMPM());
function formatAMPM() {
  var date = new Date();
  var hours = date.getHours();
  var minutes = date.getMinutes();
  var seconds = date.getSeconds();
  var ampm = hours >= 12 ? 'PM' : 'AM';
  hours = hours % 12;
  hours = hours ? hours : 12; // the hour '0' should be '12'
  minutes = minutes < 10 ? '0'+minutes : minutes;
  return strTime = date.getMonth() + '/' + date.getDay()+'/'+date.getFullYear()+' '+ hours + ':' + minutes +':'+ seconds + " " +ampm;
}

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

    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"

点击这里阅读更多。

function getTimeStamp() {
       var now = new Date();
       return ((now.getMonth() + 1) + '/' + (now.getDate()) + '/' + now.getFullYear() + " " + now.getHours() + ':'
                     + ((now.getMinutes() < 10) ? ("0" + now.getMinutes()) : (now.getMinutes())) + ':' + ((now.getSeconds() < 10) ? ("0" + now
                     .getSeconds()) : (now.getSeconds())));
}

它简单而精湛

$(document).ready(function() { var fpsOut = document.getElementById('myTime'); setInterval(function() { var d = new Date(); fpsOut.innerHTML = d; }, 1000); }); <script src=“https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js”></script> <div id=“myTime”></div>

请找到下面的提琴为例

http://jsfiddle.net/4zVxp/483/