如何使用jQuery获取当前时间

148
以下代码将以微秒为单位返回时间,例如 4565212462。

以下返回时间以微秒为单位,例如 4565212462。

alert( $.now() );

如何将其转换为人类可读的时间格式,例如(小时:分钟:秒)


2
你不需要使用jQuery来调用$.now(),因为JavaScript已经有了原生实现: https://dev59.com/zmIj5IYBdhLWcg3wPzDH#28036195 - Josh Crozier
更正:(1)这已被替换为本地的Date.now(),(2)返回的时间是毫秒,而不是微秒。 - den232
16个回答

352

你可以试试这样做:

new Date($.now());

同时,您也可以使用JavaScript按照以下方式操作:

var dt = new Date();
var time = dt.getHours() + ":" + dt.getMinutes() + ":" + dt.getSeconds();
document.write(time);


9
请注意,.getHours() 返回本地机器的时区中的小时数。如果用户的浏览器处于与您不同的时区,则会从getHours获得其他结果。.toString() 方法也是如此。在JavaScript中控制时区很棘手(必须计算您和所需时区之间的偏移量,并相应修改日期)。因此,如另一个答案中所提到的,使用moment.js听起来像是一个不错的选择。http://momentjs.com/ - Chris
4
你还应该考虑在每个get函数中使用padStart:dt.getMinutes().toString.padStart(2, '0')。这将确保数字始终为2位,其中包含填充的零,并且遵循提议的JavaScript功能-因此可以保证未来兼容性:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart - Negative Zero
2
@NegativeZero 这是一个非常有用(如果不是必要的)建议。不幸的是,在 Firefox 上它对我没有用(我没有在其他浏览器上测试过)。然而,将其重写为 String(dt.getMinutes()).padStart(2, '0') 对我有效。 - biscuitstack
moment.js 作为替代方案已经有点过时了(他们自己也这么说),而 luxon 看起来是一个很好的当前替代方案。 - Andreas Covidiot
1
@NegativeZero 应该使用toString(),变为dt.getMinutes().toString().padStart(2, '0') - Christoph S.
1
@Chris 我喜欢那些解释比直接回答更多的人。这会为像我这样的未来开发者扩展更多的知识。 - nandur

65

您需要手动获取所有的“数字”

就像这样:

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

document.write(datetime);


43
将一个Date对象转换为字符串,使用其中一个Date.prototype的转换getter,例如:
var d = new Date();
d+'';                  // "Sun Dec 08 2013 18:55:38 GMT+0100"
d.toDateString();      // "Sun Dec 08 2013"
d.toISOString();       // "2013-12-08T17:55:38.130Z"
d.toLocaleDateString() // "8/12/2013" on my system
d.toLocaleString()     // "8/12/2013 18.55.38" on my system
d.toUTCString()        // "Sun, 08 Dec 2013 17:55:38 GMT"

或者,如果您想要更加定制化的方式,可以查看Date.prototype的getter方法列表


31

你不需要使用jQuery来完成这个!

本地JavaScript实现是Date.now()

Date.now()$.now()返回相同的值:

Date.now(); // 1421715573651
$.now();    // 1421715573651
new Date(Date.now())   // Mon Jan 19 2015 20:02:55 GMT-0500 (Eastern Standard Time)
new Date($.now());     // Mon Jan 19 2015 20:02:55 GMT-0500 (Eastern Standard Time)

如果你想让时间格式为hh-mm-ss:

var now = new Date(Date.now());
var formatted = now.getHours() + ":" + now.getMinutes() + ":" + now.getSeconds();
// 20:10:58

3
你不需要为 new Date() 提供参数,因为它默认为当前时间。 - Andrew Spode
1
@Spode 啊,说得好。我不确定为什么其他答案要使用jQuery。 - Josh Crozier

21

.clock {
width: 260px;
margin: 0 auto;
padding: 30px;
color: #FFF;background:#333;
}
.clock ul {
width: 250px;
margin: 0 auto;
padding: 0;
list-style: none;
text-align: center
}

.clock ul li {
display: inline;
font-size: 3em;
text-align: center;
font-family: "Arial", Helvetica, sans-serif;
text-shadow: 0 2px 5px #55c6ff, 0 3px 6px #55c6ff, 0 4px 7px #55c6ff
}
#Date { 
font-family: 'Arial', Helvetica, sans-serif;
font-size: 26px;
text-align: center;
text-shadow: 0 2px 5px #55c6ff, 0 3px 6px #55c6ff;
padding-bottom: 40px;
}

#point {
position: relative;
-moz-animation: mymove 1s ease infinite;
-webkit-animation: mymove 1s ease infinite;
padding-left: 10px;
padding-right: 10px
}

/* Animasi Detik Kedap - Kedip */
@-webkit-keyframes mymove 
{
0% {opacity:1.0; text-shadow:0 0 20px #00c6ff;}
50% {opacity:0; text-shadow:none; }
100% {opacity:1.0; text-shadow:0 0 20px #00c6ff; } 
}

@-moz-keyframes mymove 
{
0% {opacity:1.0; text-shadow:0 0 20px #00c6ff;}
50% {opacity:0; text-shadow:none; }
100% {opacity:1.0; text-shadow:0 0 20px #00c6ff; } 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
// Making 2 variable month and day
var monthNames = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ]; 
var dayNames= ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]

// make single object
var newDate = new Date();
// make current time
newDate.setDate(newDate.getDate());
// setting date and time
$('#Date').html(dayNames[newDate.getDay()] + " " + newDate.getDate() + ' ' + monthNames[newDate.getMonth()] + ' ' + newDate.getFullYear());

setInterval( function() {
// Create a newDate() object and extract the seconds of the current time on the visitor's
var seconds = new Date().getSeconds();
// Add a leading zero to seconds value
$("#sec").html(( seconds < 10 ? "0" : "" ) + seconds);
},1000);

setInterval( function() {
// Create a newDate() object and extract the minutes of the current time on the visitor's
var minutes = new Date().getMinutes();
// Add a leading zero to the minutes value
$("#min").html(( minutes < 10 ? "0" : "" ) + minutes);
},1000);

setInterval( function() {
// Create a newDate() object and extract the hours of the current time on the visitor's
var hours = new Date().getHours();
// Add a leading zero to the hours value
$("#hours").html(( hours < 10 ? "0" : "" ) + hours);
}, 1000); 
});
</script>
<div class="clock">
<div id="Date"></div>
<ul>
<li id="hours"></li>
<li id="point">:</li>
<li id="min"></li>
<li id="point">:</li>
<li id="sec"></li>
</ul>
</div>


9

jQuery.now() 返回值:数字

描述:返回代表当前时间的数字。

此方法不接受任何参数。

$.now() 方法是表达式 (new Date).getTime() 返回的数字的简写形式。

http://api.jquery.com/jQuery.now/

在JavaScript中使用非常简单:

var d = new Date();
var time = d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();
console.log(time);

7
jQuery的$.now()是new Date().getTime()的别名,是一个Javascript内部函数。

http://api.jquery.com/jquery.now/

这会返回自1970年以来经过的秒数,通常被称为Unix时间、时代或时间戳(取决于你所处的圈子,可能不完全正确)。它可以非常方便地使用简单的数学计算日期/时间之间的差异。它没有任何时区信息,始终为UTC。

http://en.wikipedia.org/wiki/Unix_time

除了这个别名,没有必要使用jQuery,因为它在日期/时间操作方面帮助甚少。

如果您想快速而简单地以文本形式表示时间,则JavaScript Date对象具有“toString”原型,将返回ISO格式的日期时间。

new Date().toString();
//returns "Thu Apr 30 2015 14:37:36 GMT+0100 (BST)"

很有可能,您会想要自定义格式。Date对象可以提取您的相关细节,以便您可以构建自己的字符串表示。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

var d = new Date(); //without params it defaults to "now"
var t = d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();
//Will return 14:37:36

然而,由于您要求使用jQuery解决方案,所以可能是因为您正在使用旧版浏览器。如果您想执行更加具体的操作,尤其是将字符串转换为日期对象(对API响应有用),您可能需要查看Moment.js。

http://momentjs.com/

这将确保跨浏览器兼容性,并且在不必串联大量字符串的情况下具有更好的格式化!例如:
moment().format('hh:mm:ss');
//Will return 14:37:36

5

我在所有时间操作/显示方面都使用moment(无论是客户端还是node.js,如果您使用它),如果您只需要简单的格式,上面的答案就可以了,如果您正在寻找更复杂的内容,我认为moment是最好的选择。


3
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js">
</script>
<script>
    function ShowLocalDate()
    {
    var dNow = new Date();
    var localdate= (dNow.getMonth()+1) + '/' + dNow.getDate() + '/' + dNow.getFullYear() + ' ' + dNow.getHours() + ':' + dNow.getMinutes();
    $('#currentDate').text(localdate)
    }
</script>

</head>
<body>
    enter code here
    <h1>Get current local enter code here Date in JQuery</h1>
    <label id="currentDate">This is current local Date Time in JQuery</p>
    <button type="`enter code here button onclick="ShowLocalDate()">Show Local DateTime</button>

</body>
</html> 

您可以从以下链接获取更多信息:

http://www.morgantechspace.com/2013/11/Get-current-Date-time-in-JQuery.html#GetLocalDateTimeinJQuery


请注意,该链接提供了有关在jQuery中获取当前日期和时间的信息。

1
使用JavaScript本地的Date函数,您可以按照所需的方式获取小时, 分钟秒数。如果您希望以特定的方式格式化日期和时间,则可能需要实现扩展JavaScript Date原型的方法。
这里已经有一个实现了: https://github.com/jacwright/date.format

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接