JavaScript - Date and Time




JavaScript - Date and Time

Let’s meet a new built-in object: Date. It stores the date, time and provides methods for date/time management. For instance, we can use it to store creation/modification times, to measure time, or just to print out the current date.

Syntax

var dt = new Date();

var dt = new Date(milliseconds);

var dt = new Date('date string');

var dt = new Date(year, month[, date, hour, minute, second, millisecond]);

Date and time are a regular part of our everyday lives and therefore feature prominently in computer programming. In JavaScript, you might have to create a website with a calendar, a train schedule, or an interface to set up appointments. These applications need to show relevant times based on the user’s current timezone, or perform calculations around arrivals and departures or start and end times. Additionally, you might need to use JavaScript to generate a report at a certain time every day, or filter through currently open restaurants and establishments.

To achieve all of these objectives and more, JavaScript comes with the built in Date object and related methods. This tutorial will go over how to format and use date and time in JavaScript.

What is JavaScript Date and Time

JavaScript provides Date object to work with date & time including days, months, years, hours, minutes, seconds and milliseconds. The following example shows how to display current date and time using Date object in JavaScript.

Date(); //current date

//or

var currentDate = new Date(); //current date

As you can see in the above example, we can display current date and time either by calling Date as function or creating an object with new keyword. In order to work with date other than current date and time, we must create a date object by specifying different parameters in the Date constructor.

How to Get Current Date & Time in JavaScript

How do I get the current date and time in JavaScript? How to get the date in Y-m-d format in JavaScript? How do I get time in H:i:s format in JavaScript? This tutorial will help you to get the current date and time in JavaScript. You can also get date and time in your formats like Y-m-d and H:i:s formats.

Get Current Date & Time in JavaScript

Use Date() function to create an object in JavaScript with current date and time. This provides output in UTC timezone.

var today = new Date(); 

Current Date in JavaScript

Use the following script to get the current date using JavaScript in “Y-m-d” format.

var today = new Date();
var date = today.getFullYear()+'-'+(today.getMonth()+1)+'-'+today.getDate();

getFullYear() – Provides current year like 2018.

getMonth() – Provides current month values 0-11. Where 0 for Jan and 11 for Dec. So added +1 to get result.

getDate() – Provides day of the month values 1-31.

Current Date & Time Both in JavaScript

Use the following script to get the current date and time using JavaScript in “Y-m-d H:i:s” format. You can simply combine the output of the above JavaScript code in one variable as below -

var today = new Date();
var date = today.getFullYear()+'-'+(today.getMonth()+1)+'-'+today.getDate();
var time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
var dateTime = date+' '+time;

The dateTime variable contains result as -

2018-8-3 11:12:40

JavaScript Display Today Date

<!DOCTYPE html>
<html lang="en">
<head>
  <title>JavaScript today date</title>
</head>
<body>
  <script type="text/javascript"> 
    var currentDate = new Date()
    var day = currentDate.getDate()
    var month = currentDate.getMonth()
    var year = currentDate.getFullYear()
    document.write("Current Date: " + day + "-" + month + "-" + year);
  </script>
</body>
</html>

Output

Current Date: 22-5-2020

Javascript Date and Time in Detail

Javascript has a built-in Date object to handle all the time and date related operations. For example, you can display the current date/time, create a calendar, build a Pomodoro timer, code out a stop-watch, and much more.

Creating a Date Object

We can create a Date object using the new operator.

JavaScript Date and Time

One of the features of JavaScript that make it so popular is its ability to use (within the script or in the user’s browser) the local date and time. This is the output of the JavaScript Date object. A Date object contains a Number that represents milliseconds since the date 1 January 1970 UTC. The value in the object changes dynamically as the local date and time changes. You can create a Date object in various ways.

new Date();
new Date(value);
new Date(dateString);
new Date(year, monthIndex [, dayIndex [, hours [, minutes [, seconds [, milliseconds]]]]]);

If you declare a variable without the new keyword, it will return date as a string. The program below implements both these approaches.

Basic JavaScript Date and Time Functions

As the title implies, this tutorial will show you how to get the date and time from the visitor's computer and print them to the web page. You'll learn two basic techniques, How to create what's called a date object. How to extract information from that date object; the hour, minute, month, year, and so forth. A complete working example of what you'll learn here is near the end of this tutorial.

How To Create What's Called a Date Object

When a date object is created, it is stored in what's called a variable. A variable is simply the name of a place in memory that can contain information. In our example, we'll call that variable "now" because it's a good name for the current date and time. This is how you create a date object and store it in a variable -

var now = new Date();

The "new Date()" part of the above statement creates the date object. The "var now =" part causes the date object to be stored in the variable named "now".

How To Extract Information From that Date Object

Lots of information can be extracted from a date object. In this tutorial, we'll extract only what we'll need -

var hour = now.getHours();
var minute = now.getMinutes();
var second = now.getSeconds();
var monthnumber = now.getMonth();
var monthday = now.getDate();
var year = now.getYear();

Notice that the name of the variable containing the date object and a period are followed by the function name. The function extracts the information from the date object and stores it in the variable named on the left of the equal sign. All of the function names are intuitive except getDate(), which gets the day of the month rather than a date. Do not confuse "getDate()" with "new Date()" -- the former, as stated, extracts the day of the month from a date object. The latter creates the date object itself.

Printing the Date and Time

The example near the end of this tutorial demonstrates one method of obtain the date and time and printing it on a web page.

The Date

To get the date, the complete working example further below has a function called getCalendarDate() The first 13 lines of the function creates an array containing the names of the calendar month. The value obtained from the now.getMonth() function is used to determine which month name to use. The line that does that is.

var monthname = months[monthnumber];

When now.getMonth() extracts a month number, it assumes January is number 0 and December is number 11. If you prefer to print the number of the month instead of the name of the month, replace the above line with.

monthnumber = monthnumber + 1;

to conform the month number with the way most humans count them (January = 1, etc.). The getCalendarDate() function also has a line to adjust the year if the visitor is using an older browser that still assumes we're living in the 1900's. You'll recognize the line when you read the code. getCalendarDate() constructs a string of characters representing the calendar date. It then returns that construction to whatever JavaScript code calls the function.