如何使用 jQuery 获取当前时间

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20456712/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 01:10:49  来源:igfitidea点击:

How to get current time with jQuery

jquerydatetimetimeunix-timestampmicrotime

提问by Relm

The following returns time in microseconds, for example 4565212462.

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

alert( $.now() );

How do I convert it to a human readable time format, such as (hours:minutes:seconds)?

如何将其转换为人类可读的时间格式,例如 (hours:minutes:seconds)

回答by Rahul Tripathi

You may try like this:

你可以这样尝试:

new Date($.now());

Also using Javascript you can do like this:

同样使用 Javascript 你可以这样做:

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

回答by Philip G

You need to fetch all "numbers" manually

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

like this:

像这样:

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

document.write(datetime);

回答by Oriol

Convert a Dateobject to an string, using one of Date.prototype's conversion getters, for example:

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"

Or, if you want it more customized, see the list of Date.prototype's getter methods.

或者,如果您希望它更加个性化,请参阅的 getter 方法列表Date.prototype

回答by Josh Crozier

You don't need to use jQuery for this!

您不需要为此使用 jQuery!

The native JavaScript implementation is Date.now().

机 JavaScript 实现是Date.now().

Date.now()and $.now()return the same value:

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)

..and if you want the time formatted in hh-mm-ss:

..如果你想以 hh-mm-ss 格式设置时间:

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

回答by Dessy Anggita Sangganingrum

.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>

回答by softvar

jQuery.now()Returns: Number

jQuery.now()返回:数字

Description: Return a number representing the current time.

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

This method does not accept any arguments.

此方法不接受任何参数。

The $.now()method is a shorthand for the number returned by the expression (new Date).getTime().

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

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

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

It's simple to use Javascript:

使用 Javascript 很简单:

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

回答by Andrew Spode

jQuery's $.now() is an alias of new Date().getTime(), an internal Javascript function.

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

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

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

This returns the number of seconds elapsed since 1970, commonly referred to (not necessarily correctly) as Unix Time, Epoch or Timestamp, depending on the circles you fall in. It can be really handy for calculating the difference between dates/times using simple maths. It doesn't have any TimeZone information and is always UTC.

这将返回自 1970 年以来经过的秒数,通常称为(不一定正确)为 Unix 时间、纪元或时间戳,具体取决于您所在的圈子。使用简单的数学计算日期/时间之间的差异非常方便. 它没有任何时区信息,并且始终是 UTC。

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

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

There is no need to use jQuery as other than this alias, it does little else to help with date/time manipulation.

除了这个别名之外,没有必要使用 jQuery,它对日期/时间操作几乎没有帮助。

If you are looking for a quick and dirty way of representing the time in text, the Javascript Date object has a "toString" prototype that will return an ISO formatted Date Time.

如果您正在寻找一种快速而肮脏的方式来表示文本中的时间,Javascript Date 对象有一个“toString”原型,它将返回一个 ISO 格式的日期时间。

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

More than likely though, you will want to customize your formatting. The Date object has the ability to pull out your relevant details so you can build your own string representation.

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

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/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

However, as you have asked for a jQuery solution - it is perhaps likely that you are working with older browsers. If you want to do more specific things - especially interpreting strings into Date objects (useful for API responses), you might want to look at Moment.js.

但是,正如您要求的 jQuery 解决方案 - 您可能正在使用较旧的浏览器。如果您想做更具体的事情——尤其是将字符串解释为 Date 对象(对 API 响应有用),您可能需要查看 Moment.js。

http://momentjs.com/

http://momentjs.com/

This will ensure cross browser compatibility and has much improved formatting without having to concatenate lots of strings to together! For example:

这将确保跨浏览器的兼容性并大大改进格式,而无需将大量字符串连接在一起!例如:

moment().format('hh:mm:ss');
//Will return 14:37:36

回答by TheZuck

I use momentfor all my time manipulation/display needs (both client side, and node.js if you use it), if you just need a simple format the answers above will do, if you are looking for something a bit more complex, moment is the way to go IMO.

我使用moment来满足我所有的时间操作/显示需求(客户端和 node.js,如果你使用它),如果你只需要一个简单的格式,上面的答案就可以了,如果你正在寻找更复杂的东西,时刻是去海事组织的方式。

回答by Hussain Patel

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

you can get more information from below link

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

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

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

回答by Ruwanka Madhushan

Using JavaScript native Date functions you can get hours, minutesand secondsas you want. If you wish to format date and time in particular way you may want to implement a method extending JavaScript Date prototype.

使用 JavaScript 本机日期函数,您可以根据需要获取小时分钟。如果您希望以特定方式格式化日期和时间,您可能需要实现一个扩展 JavaScript 日期原型的方法。

Here is one already implemented: https://github.com/jacwright/date.format

这是一个已经实现的:https: //github.com/jacwright/date.format