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


当前回答

简单地说:-

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

您需要使用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(); 
var currentdate = new Date();

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

将. getday()方法更改为. getdate(),并将1添加到month,因为它从0开始计算月份。

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

基本JS(很好学习):我们使用Date()函数,并做所有我们需要显示日期和日期在我们的自定义格式。

var myDate = new Date(); let daysList = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']; let monthsList = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Aug', 'Oct', 'Nov', 'Dec']; let date = myDate.getDate(); let month = monthsList[myDate.getMonth()]; let year = myDate.getFullYear(); let day = daysList[myDate.getDay()]; let today = `${date} ${month} ${year}, ${day}`; let amOrPm; let twelveHours = function (){ if(myDate.getHours() > 12) { amOrPm = 'PM'; let twentyFourHourTime = myDate.getHours(); let conversion = twentyFourHourTime - 12; return `${conversion}` }else { amOrPm = 'AM'; return `${myDate.getHours()}`} }; let hours = twelveHours(); let minutes = myDate.getMinutes(); let currentTime = `${hours}:${minutes} ${amOrPm}`; console.log(today + ' ' + currentTime);


Node JS(快速简单):使用(npm安装日期和时间)安装npm页面,然后运行以下命令。

let nodeDate = require('date-and-time');
let now = nodeDate.format(new Date(), 'DD-MMMM-YYYY, hh:mm:ss a');
console.log(now);