在JavaScript中获取当前date和时间

我有一个脚本,在JavaScript中打印当前的date和时间,但DATE是错误的。 这里是代码:

 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

任何帮助? 谢谢

调用.getMonth()您需要添加+1以显示正确的月份。 Javascript计数总是从0开始(看这里检查为什么),所以调用.getMonth()可能会返回4而不是5

所以在你的代码中我们可以使用currentdate.getMonth()+1来输出正确的值。 此外:

  • .getDate()返回月份的一天< – 这是你想要的
  • .getDay()Date对象的一个​​独立方法,它将返回一个表示当前星期几的整数(0-6) 0 == Sunday

所以你的代码应该是这样的:

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

JavaScriptdate实例inheritance自Date.prototype。 您可以修改构造函数的原型对象,以影响由JavaScript Date实例inheritance的属性和方法

您可以使用Date对象的原型构造函数,并创build一个Date对象的新方法来返回今天的date和时间。 这些新的方法或属性将被Date对象的所有实例inheritance,因此,如果您需要重新使用此function,它将特别有用。

 // For todays date; Date.prototype.today = function () { return ((this.getDate() < 10)?"0":"") + this.getDate() +"/"+(((this.getMonth()+1) < 10)?"0":"") + (this.getMonth()+1) +"/"+ this.getFullYear(); } // For the time now Date.prototype.timeNow = function () { return ((this.getHours() < 10)?"0":"") + this.getHours() +":"+ ((this.getMinutes() < 10)?"0":"") + this.getMinutes() +":"+ ((this.getSeconds() < 10)?"0":"") + this.getSeconds(); } 

您可以通过执行以下操作简单地检索date和时间:

 var newDate = new Date(); var datetime = "LastSync: " + newDate.today() + " @ " + newDate.timeNow(); 

或者直接调用这个方法,

 var datetime = "LastSync: " + new Date().today() + " @ " + new Date().timeNow(); 

要得到时间和date,你应该使用

  new Date().toLocaleString(); >> "09/08/2014, 2:35:56 AM" 

只能得到你应该使用的date

  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" 

在这里阅读更多。

如果你想真正的MySQL风格的date时间使用这个

2013/10/04 08:51:32

  function getDateTime() { var now = new Date(); var year = now.getFullYear(); var month = now.getMonth()+1; var day = now.getDate(); var hour = now.getHours(); var minute = now.getMinutes(); var second = now.getSeconds(); if(month.toString().length == 1) { var month = '0'+month; } if(day.toString().length == 1) { var day = '0'+day; } if(hour.toString().length == 1) { var hour = '0'+hour; } if(minute.toString().length == 1) { var minute = '0'+minute; } if(second.toString().length == 1) { var second = '0'+second; } var dateTime = year+'/'+month+'/'+day+' '+hour+':'+minute+':'+second; return dateTime; } 

只要使用:

 var d = new Date(); document.write(d.toLocaleString()); document.write("<br>"); 
 var currentdate = new Date(); var datetime = "Last Sync: " + currentdate.getDate() + "/"+(currentdate.getMonth()+1) + "/" + currentdate.getFullYear() + " @ " + currentdate.getHours() + ":" + currentdate.getMinutes() + ":" + currentdate.getSeconds(); 

.getDay()方法更改为.GetDate()并将其添加到月,因为它从0开始计数。

您需要使用getDate()来获取date部分。 getDay()函数返回星期数(星期日= 0,星期一= 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 (4月)。

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

这应该做的伎俩:

 function dateToString(date) { var month = date.getMonth() + 1; var day = date.getDate(); var dateOfString = (("" + day).length < 2 ? "0" : "") + day + "/"; dateOfString += (("" + month).length < 2 ? "0" : "") + month + "/"; dateOfString += date.getFullYear(); return dateOfString; } var currentdate = new Date(); var datetime = "Last Sync: "; datetime += dateToString(currentdate ); datetime += + currentdate.getHours() + ":" + currentdate.getMinutes() + ":" + currentdate.getSeconds(); 

获取当前的date和时间

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

.getDay返回星期几。 你需要.getDate。 .getMonth返回0到11之间的值。您需要将结果加1以获得“人”月份数。

这个小代码很容易,到处都是。

 <p id="dnt"></p> <script> document.getElementById("dnt").innerHTML = Date(); </script> 

有devise的空间

 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()))); } 
 dt= new Date(); alert(dt.toISOString().substring(8,10) + "/" + dt.toISOString().substring(5,7)+ "/" + dt.toISOString().substring(0,4) + " " + dt.toTimeString().substring(0,8)) 

这个问题相当古老,答案也是如此。 我们现在可以使用moment.js来获取当前的date,而不是那些怪异的function,这实际上很容易。 所有必须做的事情是在我们的项目中包含moment.js并且得到一个很好的date,例如:

 moment().format("dddd, MMMM Do YYYY, h:mm:ss a"); 

我认为这使得处理JavaScriptdate更容易。

我find了从这里获取当前date和时间的最简单方法 – 如何使用JavaScript获取当前date和时间

 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; 
 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: 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 
 var datetime = new Date().toLocaleString().slice(0,9) +" "+new Date(new Date()).toString().split(' ')[4]; console.log(datetime); 

我想我很晚才分享我的答案,但我认为这将是值得的。

 function __getCurrentDateTime(format){ var dt=new Date(),x,date=[]; date['d']=dt.getDate(); date['dd']=dt.getDate()>10?dt.getDate():'0'+dt.getDate(); date['m']=dt.getMonth()+1; date['mm']=(dt.getMonth()+1)>10?(dt.getMonth()+1):'0'+(dt.getMonth()+1); date['yyyy']=dt.getFullYear(); date['yy']=dt.getFullYear().toString().slice(-2); date['h']=(dt.getHours()>12?dt.getHours()-12:dt.getHours()); date['hh']=dt.getHours(); date['mi']=dt.getMinutes(); date['mimi']=dt.getMinutes()<10?('0'+dt.getMinutes()):dt.getMinutes(); date['s']=dt.getSeconds(); date['ss']=dt.getSeconds()<10?('0'+dt.getSeconds()):dt.getSeconds(); date['sss']=dt.getMilliseconds(); date['ampm']=(dt.getHours()>=12?'PM':'AM'); x=format.toLowerCase(); x=x.indexOf('dd')!=-1?x.replace(/(dd)/i,date['dd']):x.replace(/(d)/i,date['d']); x=x.indexOf('mm')!=-1?x.replace(/(mm)/i,date['mm']):x.replace(/(m)/i,date['m']); x=x.indexOf('yyyy')!=-1?x.replace(/(yyyy)/i,date['yyyy']):x.replace(/(yy)/i,date['yy']); x=x.indexOf('hh')!=-1?x.replace(/(hh)/i,date['hh']):x.replace(/(h)/i,date['h']); x=x.indexOf('mimi')!=-1?x.replace(/(mimi)/i,date['mimi']):x.replace(/(mi)/i,date['mi']); if(x.indexOf('sss')!=-1){ x=x.replace(/(sss)/i,date['sss']); } x=x.indexOf('ss')!=-1?x.replace(/(ss)/i,date['ss']):x.replace(/(s)/i,date['s']); if(x.indexOf('ampm')!=-1){ x=x.replace(/(ampm)/i,date['ampm']); } return x; } console.log(__getCurrentDateTime()); //returns in dd-mm-yyyy HH:MM:SS console.log(__getCurrentDateTime('dd-mm-yyyy')); //return in 05-12-2016 console.log(__getCurrentDateTime('dd/mm*yyyy')); //return in 05/12*2016 console.log(__getCurrentDateTime('hh:mimi:ss')); //return in 13:05:30 

console.log(__ getCurrentDateTime('h:mi:ss ampm')); //在1:5:30 PM返回

 function UniqueDateTime(format='',language='en-US'){ //returns a meaningful unique number based on current time, and milliseconds, making it virtually unique //eg : 20170428-115833-547 //allows personal formatting like more usual :YYYYMMDDHHmmSS, or YYYYMMDD_HH:mm:SS var dt = new Date(); var modele="YYYYMMDD-HHmmSS-mss"; if (format!==''){ modele=format; } modele=modele.replace("YYYY",dt.getFullYear()); modele=modele.replace("MM",(dt.getMonth()+1).toLocaleString(language, {minimumIntegerDigits: 2, useGrouping:false})); modele=modele.replace("DD",dt.getDate().toLocaleString(language, {minimumIntegerDigits: 2, useGrouping:false})); modele=modele.replace("HH",dt.getHours().toLocaleString(language, {minimumIntegerDigits: 2, useGrouping:false})); modele=modele.replace("mm",dt.getMinutes().toLocaleString(language, {minimumIntegerDigits: 2, useGrouping:false})); modele=modele.replace("SS",dt.getSeconds().toLocaleString(language, {minimumIntegerDigits: 2, useGrouping:false})); modele=modele.replace("mss",dt.getMilliseconds().toLocaleString(language, {minimumIntegerDigits: 3, useGrouping:false})); return modele; } 

我需要弄明白这个后果的石板。 这是我从几个不同的来源采取元素后想出的 – 格式是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 

它简单而精湛

  $(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> 

检查这可能是它会为你工作

 <script language="JavaScript"> var dayarray=new Array("Sunday","Monday", "Tuesday","Wednesday","Thursday","Friday","Saturday") var montharray=new Array("January","February","March", "April","May","June","July","August","September", "October","November","December") function getthedate(){ var mydate=new Date() var year=mydate.getYear() if (year < 1000) year+=1900 var day=mydate.getDay() var month=mydate.getMonth() var daym=mydate.getDate() if (daym<10) daym="0"+daym var hours=mydate.getHours() var minutes=mydate.getMinutes() var seconds=mydate.getSeconds() var dn="AM" if (hours>=12) dn="PM" if (hours>12){ hours=hours-12 } if (hours==0) hours=12 if (minutes<=9) minutes="0"+minutes if (seconds<=9) seconds="0"+seconds //change font size here var cdate="<small><font color='000000' face='Arial'><b>"+dayarray[day]+", "+montharray[month]+" "+daym+", "+year+" "+hours+":" +minutes+":"+seconds+" "+dn +"</b></font></small>" if (document.all) document.all.clock.innerHTML=cdate else if (document.getElementById) document.getElementById("clock").innerHTML=cdate else document.write(cdate) } if (!document.all&&!document.getElementById) getthedate() function goforit(){ if (document.all||document.getElementById) setInterval("getthedate()",1000) } </script> enter code here <span id="clock"></span>