jQuery로 현재 시간을 얻는 방법


129

다음은 시간을 마이크로 초 (예 : 4565212462)로 반환합니다.

alert( $.now() );

(시 : 분 : 초) 와 같이 사람이 읽을 수있는 시간 형식으로 변환하려면 어떻게합니까 ?


1
$.now()JavaScript에는 기본 구현이 있으므로 jQuery가 필요하지 않습니다 . stackoverflow.com/questions/20456712/…
— Josh Crozier

수정 사항 : (1) 기본 Date.now ()로 바뀌 었으며 (2) 반환 된 시간은 마이크로 초가 아니라 밀리 초입니다.
— den232

답변:


304

다음과 같이 시도해보십시오.

new Date($.now());

또한 Javascript를 사용하면 다음과 같이 할 수 있습니다.

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


7
.getHours ()는 로컬 컴퓨터의 시간대로 시간을 반환합니다. 사용자가 다른 시간대의 브라우저를 사용하는 경우 getHours에서 다른 결과를 얻습니다. .toString () 메소드에서도 마찬가지입니다. 자바 스크립트에서 시간대를 제어하는 ​​것은 까다 롭습니다 (원하는 시간대와 원하는 시간대 사이의 오프셋을 계산하고 그에 따라 날짜를 수정해야 함). 다른 답변에서 언급했듯이 moment.js를 사용하는 것이 좋습니다. momentjs.com
— Chris

1
또한 각 get에 padStart를 포함시키는 것을 고려해야합니다. 차후 증명 됨 : developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
— 음수 0

2
@NegativeZero 정말 유용한 (필수적이지 않은 경우) 제안입니다. 불행히도 Firefox에서는 작동하지 않았습니다 (다른 브라우저에서는 테스트하지 않았습니다). 그러나 String (dt.getMinutes ()). padStart (2, '0')로 다시 작성하면 효과가 있습니다.
— 비스킷

54

모든 "숫자"를 수동으로 가져와야합니다.

이처럼 :

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

document.write(datetime);


39

예를 들어 다음 의 변환 getterDate 중 하나를 사용하여 객체를 문자열로 변환합니다 .Date.prototype

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.prototypegetter 메소드 목록을 참조하십시오 .


25

이를 위해 jQuery를 사용할 필요가 없습니다!

기본 자바 스크립트 구현은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

1
기본값이 now이므로 new Date ()에 매개 변수를 제공 할 필요가 없습니다.
— Andrew Spode

1
@ 스 포드 아, 좋은 지적. 왜 다른 답변이 jQuery를 사용했는지 모르겠습니다.
— Josh Crozier

17

.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()메서드는 expression에서 반환 한 숫자의 약어입니다 (new Date).getTime().

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

자바 스크립트를 사용하는 것은 간단합니다 :

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

5

jQuery의 $ .now ()는 내부 Javascript 함수 인 new Date (). getTime ()의 별칭입니다.

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

이것은 1970 년 이후 경과 한 시간 (초)을 반환하며 원에 따라 일반적으로 Unix Time, Epoch 또는 Timestamp라고 칭합니다. 간단한 수학을 사용하여 날짜 / 시간의 차이를 계산하는 데 매우 유용 할 수 있습니다. . TimeZone 정보가 없으며 항상 UTC입니다.

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

이 별명 외에 jQuery를 사용할 필요가 없으며 날짜 / 시간 조작에 도움이되지 않습니다.

텍스트로 시간을 표현하는 빠르고 더러운 방법을 찾고 있다면 Javascript Date 객체에는 ISO 형식의 Date Time을 반환하는 "toString"프로토 타입이 있습니다.

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 솔루션을 요청한 경우 이전 브라우저로 작업 중일 수 있습니다. 보다 구체적인 작업, 특히 문자열을 Date 객체로 해석 (API 응답에 유용)하려는 경우 Moment.js를 참조하십시오.

http://momentjs.com/

이렇게하면 브라우저 간 호환성이 보장되고 많은 문자열을 함께 연결하지 않고도 서식이 훨씬 향상됩니다! 예를 들면 다음과 같습니다.

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

4

나는 모든 시간 조작 / 디스플레이 요구 (사용하는 경우 클라이언트 측과 node.js 모두)에 순간 을 사용합니다. 단순한 형식이 필요하면 위의 답변이 수행 할 것입니다. 좀 더 복잡한 것을 찾고 있다면, 순간은 IMO를가는 길입니다.


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




0

ISO8601SQL 에 대한 현지 시간으로 TIMESTAMP다음을 시도 할 수 있습니다.

var tzoffset = (new Date()).getTimezoneOffset() * 60000;
var localISOTime = (new Date(Date.now() - tzoffset))
  .toISOString()
  .slice(0, 19)
  .replace('T', ' ');
$('#mydatediv').val(localISOTime);


0

<p id="date"></p>

<script>
var d = new Date();
document.getElementById("date").innerHTML = d.toTimeString();
</script>

JS에서 Date ()를 사용할 수 있습니다.


0

다음과 같은

function gettzdate(){
    var fd = moment().format('YYYY-MM-DDTHH:MM:ss');
    return fd ; 
}

현재 날짜를 <input type="datetime-local">

당사 사이트를 사용함과 동시에 당사의 쿠키 정책과 개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.