jqyery

How to get current time using jQuery


In this article, you will learn about how to get current time using jQuery.

jQuery is a lightweight and feature-rich JavaScript library. The purpose of jQuery is to write less and do more. You can do many interesting things and give users a better experience by using jQuery. Getting current time is one of them. In this article, you will learn how to get the current time when a user clicks on a button by using jQuery. Before doing that I would like to introduce you to the Date Object that comes with JavaScript.

In JavaScript, Date Objects represents a single moment in time and you can get access to the current time by using Date.now() method. Let’s see the below code example:

console.log(Date.now())

//Output: 1642428809226

You can see that it simply represents a number and the time has been printed into milliseconds.

In jQuery, you may get the time in a nice formatted way. To do so you may use jQuery.now() or Date.now(). Let’s see an example of getting current time by using Date.now() method in jQuery.

Important: It is recommended to use Date.now() instead of using jQuery.now() as this API has been deprecated in jQuery 3.3.

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style.css">
    <title>jQuery current date</title>
</head>
<body>
		<h1>jQuery - Get Current Date</h1>
		<input type="button" id="btn" value="Get Date (DD/MM/YYYY)"/>
		<p id="showDate">
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script src="app.js"></script>
</body>
</html>

Here, we simply link our necessary files such as the custom js file, jQuery file from CDN and simply take an input field.

jQuery

$(document).ready(function(){
  let date = new Date();
  $("#btn").click(function(){
    let value = `${date.getDate()}/${date.getMonth() + 1}/${date.getFullYear()}`
    $("#showDate").text(value);
  });			
});

Here, we implement the functionality to get the current time and we have also used es6 features that is template engine to format our time. Let’s see the output below

Output

get current time using jQuery

You can see that we are getting the current date and this is the beauty of jQuery. You can do more things by writing less amount of code. To make things attractive, we have used some CSS but that is not so important you may style on the basis of your own interest.


Share on social media

//