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


当前回答

我需要在后期特效里弄清楚这一点。以下是我从几个不同的来源获取元素后得出的结论——格式是MM/DD/YYYY HH:MM AM/PM

D = new Date(Date(00));
M = D.getMonth()+1;
H = D.getHours();
Mi = D.getMinutes();

N = "AM"
if (H >= 12)
N = "PM"
if (H > 12)
{
H = H-12
}

amtOfZeroes = 2;
isNeg = false;

if (M < 0)
{
M = Math.abs(M);
isNeg = true;
}
Mo = Math.round(M) + "";
while(Mo.length < amtOfZeroes)
{

Mo = "0" + Mo; 
}
if (isNeg)
Mo = "-" + Mo;

if (H < 0)
{
H = Math.abs(H);
isNeg = true;
}
Ho = Math.round(H) + "";
while(Ho.length < amtOfZeroes)
{
Ho = "0" + Ho; 
}
if (isNeg)
Ho = "-" + Ho;

if (Mi < 0)
{
Mi = Math.abs(Mi);
isNeg = true;
}
Min = Math.round(Mi) + "";
while(Min.length < amtOfZeroes)
{
Min = "0" + Min; 
}
if (isNeg)
Min = "-" + Min;

T = Ho + ":" + (Min)

Mo + "/" + D.getDate() + "/" + D.getFullYear() + "  " + T + " " + N

其他回答

试试这个:

var today = new Date();
var date = today.getFullYear()+'-'+(today.getMonth()+1)+'-'+today.getDate();
var time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
var dateTime = date+' '+time;

输出:

2022-3-3 15:52:45

我发现了最简单的方法来获得当前的日期和时间在JavaScript从这里-如何获得当前的日期和时间使用JavaScript

var today = new Date();
var date = today.getFullYear()+'-'+(today.getMonth()+1)+'-'+today.getDate();
var time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
var CurrentDateTime = date+' '+time;

简单地说:-

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

参考

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

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

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

您需要使用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();