How to get current time with jQuery
Asked Answered
L

16

148

The following returns time in microseconds, for example 4565212462.

alert( $.now() );

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

Leontina answered 8/12, 2013 at 17:45 Comment(2)
You don't need jQuery for $.now() since JavaScript has a native implementation: #20457212Article
Corrections: (1) This has been replaced with the native Date.now(), and (2) The time returned is in milliseconds, not microseconds.Exchangeable
C
352

You may try like this:

new Date($.now());

Also using Javascript you can do like this:

var dt = new Date();
var time = dt.getHours() + ":" + dt.getMinutes() + ":" + dt.getSeconds();
document.write(time);
Coaction answered 8/12, 2013 at 17:48 Comment(6)
Please note that .getHours() returns the hours in the time zone of the local machine. If the user has their browser in another time zone than you, they will get other results from getHours. This also holds true for the .toString() method. Controlling the time zone in javascript is tricky (you have to calculate the offset between your and the desired time zone and modify the date accordingly). So as mentioned in another answer, using moment.js sounds like a good idea. momentjs.comAnticoagulant
You should also consider including padStart to each get: dt.getMinutes().toString.padStart(2, '0') This will ensure that the numbers remain 2 digits long with a padded zero, and it follows proposed javascript functionality - so pretty future proofed: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…Corum
@NegativeZero A really useful (if not essential) suggestion. Unfortunately it didn't work for me on Firefox (I didn't test on other browsers). However, rewriting it as String(dt.getMinutes()).padStart(2, '0') works for me.Vassell
moment.js as alternative is kind of deprecated (say it themselves) and luxon seems a good current alternativeThorlay
@NegativeZero It must be dt.getMinutes().toString().padStart(2, '0') with toString().Gatha
@Anticoagulant i love peoples who explain more than answer it self. It just expanding more knowledge fo future dev like me.Pernod
C
65

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);
Crawl answered 8/12, 2013 at 17:50 Comment(0)
A
43

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

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.

Arun answered 8/12, 2013 at 17:49 Comment(0)
A
31

You don't need to use jQuery for this!

The native JavaScript implementation is Date.now().

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

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:

var now = new Date(Date.now());
var formatted = now.getHours() + ":" + now.getMinutes() + ":" + now.getSeconds();
// 20:10:58
Article answered 20/1, 2015 at 1:8 Comment(2)
You don't need to provide parameters to new Date() as it defaults to now.Amanita
@Spode Ah, good point. I'm not sure why other answers were using jQuery then.Article
P
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>
Pistachio answered 4/5, 2015 at 19:18 Comment(0)
R
9

jQuery.now() Returns: Number

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

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

It's simple to use Javascript:

var d = new Date();
var time = d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();
console.log(time);
Readymix answered 8/12, 2013 at 17:50 Comment(0)
A
7

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

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.

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.

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.

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.

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.

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
Amanita answered 30/4, 2015 at 13:53 Comment(0)
I
5

I use moment for 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.

Inhume answered 2/5, 2015 at 20:21 Comment(0)
G
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> 

you can get more information from below link

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

Garris answered 4/5, 2015 at 21:51 Comment(0)
E
1

Try

console.log(
  new Date().toLocaleString().slice(9, -3)
  , new Date().toString().slice(16, -15)
);
Egocentric answered 1/5, 2015 at 6:45 Comment(0)
B
1

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

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

Bipack answered 4/5, 2015 at 6:14 Comment(0)
S
1

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

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

You can use Date() in JS.

Sherri answered 10/10, 2019 at 7:32 Comment(0)
S
1

The following

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

works for forcing the current date onto a <input type="datetime-local">

Saldivar answered 28/2, 2020 at 6:38 Comment(0)
M
1

var dt = new Date();
var time = dt.getHours() + ":" + dt.getMinutes() + ":" + dt.getSeconds();
document.write(time);
Machinery answered 18/4, 2022 at 7:25 Comment(1)
Your answer could be improved by adding more information on what the code does and how it helps the OP.Blowhole
R
0

For local time in ISO8601 for SQL TIMESTAMP you could try:

var tzoffset = (new Date()).getTimezoneOffset() * 60000;
var localISOTime = (new Date(Date.now() - tzoffset))
  .toISOString()
  .slice(0, 19)
  .replace('T', ' ');
$('#mydatediv').val(localISOTime);
Race answered 22/11, 2017 at 2:6 Comment(0)
S
0

console.log(
  new Date().toLocaleString().slice(9, -3)
  , new Date().toString().slice(16, -15)
);
Stroh answered 17/4, 2019 at 9:45 Comment(1)
Add relevant explanation to your answerTiebout

© 2022 - 2024 — McMap. All rights reserved.