Getting current date and time in JavaScript
我有一个用javascript打印当前日期和时间的脚本,但是
1 2 3 4 5 | var currentdate = new Date(); var datetime ="Last Sync:" + currentdate.getDay() +"/"+currentdate.getMonth() +"/" + currentdate.getFullYear() +" @" + currentdate.getHours() +":" + currentdate.getMinutes() +":" + currentdate.getSeconds(); |
打印
有什么帮助吗?谢谢
调用
所以在您的代码中,我们可以使用
.GetDate() 返回月日<-这是您想要的日期.getDay() 是Date 对象的一种独立方法,它返回一个整数,表示一周的当前日期(0-6)0 == Sunday 等。
所以您的代码应该如下所示:
1 2 3 4 5 6 7 | var currentdate = new Date(); var datetime ="Last Sync:" + currentdate.getDate() +"/" + (currentdate.getMonth()+1) +"/" + currentdate.getFullYear() +" @" + currentdate.getHours() +":" + currentdate.getMinutes() +":" + currentdate.getSeconds(); |
JavaScript Date instances inherit from Date.prototype. You can modify the constructor's prototype object to affect properties and methods inherited by JavaScript Date instances
您可以使用
1 2 3 4 5 6 7 8 9 | // 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(); } |
然后,您可以通过执行以下操作来检索日期和时间:
1 2 | var newDate = new Date(); var datetime ="LastSync:" + newDate.today() +" @" + newDate.timeNow(); |
或者直接调用方法,这样-
1 | var datetime ="LastSync:" + new Date().today() +" @" + new Date().timeNow(); |
为了得到你应该使用的时间和日期
1 2 3 | new Date().toLocaleString(); >>"09/08/2014, 2:35:56 AM" |
只得到你应该使用的日期
1 2 3 | new Date().toLocaleDateString(); >>"09/08/2014" |
只得到你应该使用的时间
1 2 3 | new Date().toLocaleTimeString(); >>"2:35:56 AM" |
或者,如果您只希望时间格式为
1 2 3 4 | new Date().toLocaleTimeString('en-US', { hour12: false, hour:"numeric", minute:"numeric"}); >>"02:35" |
或者英国英语
1 2 3 4 | new Date().toLocaleTimeString('en-GB', { hour:"numeric", minute:"numeric"}); >>"02:35" |
在这里阅读更多。
对于这个真正的mysql样式,使用下面的函数:
- 如果单击下面的"运行代码段"按钮
- 它将显示一个简单的实时数字时钟示例
- 演示将出现在代码段下面。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 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) { month = '0'+month; } if(day.toString().length == 1) { day = '0'+day; } if(hour.toString().length == 1) { hour = '0'+hour; } if(minute.toString().length == 1) { minute = '0'+minute; } if(second.toString().length == 1) { second = '0'+second; } var dateTime = year+'/'+month+'/'+day+' '+hour+':'+minute+':'+second; return dateTime; } // example usage: realtime clock setInterval(function(){ currentTime = getDateTime(); document.getElementById("digital-clock").innerHTML = currentTime; }, 1000); |
1 |
只需使用:
1 2 3 | var d = new Date(); document.write(d.toLocaleString()); document.write(""); |
1 2 3 4 5 6 | var currentdate = new Date(); var datetime ="Last Sync:" + currentdate.getDate() +"/"+(currentdate.getMonth()+1) +"/" + currentdate.getFullYear() +" @" + currentdate.getHours() +":" + currentdate.getMinutes() +":" + currentdate.getSeconds(); |
将
这应该可以做到:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | 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(); |
另外,
演示:http://jsfiddle.net/4zvxp/
您需要使用getDate()来获取日期部分。getday()函数返回日期(星期日=0,星期一=1…),getmonth()返回基于0的索引,因此需要将其递增1。
1 2 3 4 5 6 | var currentdate = new Date(); var datetime ="Last Sync:" + currentdate.getDate() +"/"+ (parseInt(currentdate.getMonth()) + 1) +"/" + currentdate.getFullYear() +" @" + currentdate.getHours() +":" + currentdate.getMinutes() +":" + currentdate.getSeconds(); |
获取当前日期和时间
1 2 3 | var now = new Date(); var datetime = now.getFullYear()+'/'+(now.getMonth()+1)+'/'+now.getDate(); datetime += ' '+now.getHours()+':'+now.getMinutes()+':'+now.getSeconds(); |
我找到了从这里获取当前日期和时间的最简单方法-如何使用javascript获取当前日期和时间
1 2 3 4 | 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; |
.getday返回星期几。你需要。改为获取日期。.getmonth返回0到11之间的值。您需要在结果中添加1以获得"人类"月份号。
1 2 3 4 5 6 | 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()))); } |
这个问题很古老,答案也很清楚。现在我们可以使用moment.js来获取当前日期,而不是那些可怕的函数,这实际上非常简单。所有需要做的就是在我们的项目中包含moment.js,并通过以下方式获得一个格式良好的日期:
1 | moment().format("dddd, MMMM Do YYYY, h:mm:ss a"); |
我认为这使得在JavaScript中处理日期更加容易。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | function UniqueDateTime(format='',language='en-US'){ //returns a meaningful unique number based on current time, and milliseconds, making it virtually unique //e.g : 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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 | 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 |
基本JS(很好学习):我们使用日期()函数,并尽我们所能以自定义格式显示日期和日期。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | 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); |
节点JS(Quick&Easy):使用(NPM安装日期和时间)安装NPM分页,然后运行以下命令。
1 2 3 | let nodeDate = require('date-and-time'); let now = nodeDate.format(new Date(), 'DD-MMMM-YYYY, hh:mm:ss a'); console.log(now); |
这个小代码很容易,在任何地方都可以工作。
1 2 3 4 | <p id="dnt"> </p> document.getElementById("dnt").innerHTML = Date(); |
有空间设计
如果有人在寻找功能
1 2 3 4 5 6 7 8 9 10 11 12 | 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; } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | 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 |
1 2 3 4 5 | dt= new Date(); alert(dt.toISOString().substring(8,10) +"/" + dt.toISOString().substring(5,7)+"/" + dt.toISOString().substring(0,4) +"" + dt.toTimeString().substring(0,8)) |
我的正确答案是使用这个小小的JS:https://github.com/rhroyston/clock-js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | 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 |
1 2 | var datetime = new Date().toLocaleString().slice(0,9) +""+new Date(new Date()).toString().split(' ')[4]; console.log(datetime); |
我想我很晚才告诉大家我的答案,但我认为这是值得的。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | 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(uugetcurrendtime('h:mi:ss ampm'));//下午1:5:30返回
它简单而卓越
1 2 3 4 5 6 7 | $(document).ready(function () { var fpsOut = document.getElementById('myTime'); setInterval(function () { var d = new Date(); fpsOut.innerHTML = d; }, 1000); }); |
1 | <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"> |
请找下面这个例子的小提琴手
http://jsfiddle.net/4zvxp/483/
看看这个可能对你有用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 | <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'>"+dayarray[day]+", "+montharray[month]+""+daym+","+year+""+hours+":" +minutes+":"+seconds+""+dn +"</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) } enter code here <span id="clock"></span> |
1 2 3 4 5 6 7 | <p id="DateTimeBox">Click The Button To Show Date And Time </p> <button onclick="ShowDate();"> Show Date </button> function ShowDate() { document.getElementById('DateTimeBox').innerHTML = Date(); } |