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


当前回答

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())));
}

其他回答

简单地说:-

console.log(new Date().toLocaleString());

参考

获取当前日期和时间

var now = new Date(); 
  var datetime = now.getFullYear()+'/'+(now.getMonth()+1)+'/'+now.getDate(); 
  datetime += ' '+now.getHours()+':'+now.getMinutes()+':'+now.getSeconds(); 

只使用:

var d = new Date();
document.write(d.toLocaleString());
document.write("<br>");

我开发史蒂夫的答案,以确切地了解OP需要什么

new Date().toLocaleString().replace(',','')

.toLocaleString console.log(新日期()().replace (',',''));

这是英国时区的例子。为特定时区设置偏移量。 例如:印度:+05:30,英国:+1

 function realUKTime() {
        // create Date object for current location
        var d = new Date();
        offset ='+1';
       
        // convert to msec
        // subtract local time zone offset
        // get UTC time in msec
        var utc = d.getTime() + (d.getTimezoneOffset() * 60000);

        // create new Date object for different city
        // using supplied offset
        var nd = new Date(utc + (3600000*offset));

        // return time as a string
        var s = nd.getSeconds();
        var i = nd.getMinutes();
        var h = nd.getHours();
        var cDate =  nd.getDate();
        var m =  nd.getUTCMonth();
        var y = nd.getFullYear();

       var newUkTime = nd.toDateString() + " "+ (Number(h)-1)+":"+i+':'+s
        $("#realTime").html(newUkTime);

    }

    setInterval(realUKTime(),1000);

输出::Mon 12月27日2021 12:6:3