Welcome to another tutorial, here you will learn how to work with data and time in JavaScript.
In JavaScript, a date object is a built-in object. The date object makes it possible for you to get the user's local time by accessing the computer system clock through the browser. It also provides several methods for managing, formatting, and manipulating dates and times.
You need to learn how to create a Date object before you start working with the date and time. However, dates don't have a corresponding literal form (i.e all data objects need to be created using the Date constructor function which is Date()), unlike other built-in objects, such as arrays or functions.
In JavaScript, there are four different ways to create a Date object.
A new Date object can simply be declared without initializing its value. Hence, the date and time value will be set to the current date and time on the user's device on which the script is run.
A Date object can be initialized by passing the following parameters separated by the use of commas: year, month, day, hours, minutes, seconds, and milliseconds. The year and month parameters are important while, other parameters are optional.
var d = new Date(2022,07,15,14,35,20,50);
document.write(d);
This date is represented as 15 Aug 2022 at 14:35:20 and 50 milliseconds, but you can ignore the time part and specify just the date part if you wish.
In JavaScript, you to create a Date object by passing the string representing a date, or a date and time, as shown in the example below:
var d = new Date("15 April 2022");
document.write(d);
This date represents 15 April 2022, but, you can also specify strings like ‘Apr 15, 2022’, or any of a number of valid variations, as JavaScript will automatically handle that.
A Date object can also be defined by passing the number of milliseconds since January 1, 1970, at 00:00:00 GMT. This is because1970 was the year when the UNIX operating system was formally introduced and is known as the UNIX epoch
var d = new Date(1660458141499);
document.write(d);
The date in the example above represents Sun Aug 14 2022 11:52:21 05:30:00 GMT+0530.
When you have created an instance of the Date object, you can then use its methods to perform various tasks, like getting different components of a date, setting or modifying the individual date and time value, and so on.
In the next sections, we will look at these methods in detail.
Note: The shortcuts called "literals" are provided by JavaScript for creating most of the native objects without having to use the new operator, like new Object(), new Array(), and so on.
To get the current date and time, you can create a new Date object without passing any parameters. However, it will create an object with the current date and time. below is an example:
var now = new Date();
alert(now); // Display the current date and time
The output of the example above will look like this (depending on time zone offset):
The JavaScript Date object provides numerous methods, including toLocaleDateString(), toDateString(), and so on.
If you want to generate date strings in different formats. You can do it like this:
var d = new Date();
alert(d.toDateString()); // Display an abbreviated date string
alert(d.toLocaleDateString()); // Display a localized date string
alert(d.toISOString()); // Display the ISO standardized date string
alert(d.toUTCString()); // Display a date string converted to UTC time
alert(d.toString()); // Display the full date string with local time zone
More so, you can also use the toTimeString(), toLocaleTimeString() methods of the Date object to generate time strings, as shown in the example below:
var d = new Date();
alert(d.toTimeString()); // Display the time portion of the date
alert(d.toLocaleTimeString()); // Display a localized time string
Once you have a well-defined date object, several methods are available to you for the extraction details from it; such as the month, date, hours or minutes value, etc.
The sections below describe the various methods of extracting individual pieces of information from a Date object.
The methods such as getFullYear(), getMonth(), getDay(), are provided by the Date object, that you can use to extract the specific date components from the Date object, such as year, day of the month, day of the week, and so on respectively. The example illustrates how to get specific date components from the Date object using these methods:
var d = new Date();
// Extracting date part
alert(d.getDate()); // Display the day of the month
alert(d.getDay()); // Display the number of days into the week (0-6)
alert(d.getMonth()); // Display the number of months into the year (0-11)
alert(d.getFullYear()); // Display the full year (four digits)
The method getDay() returns a number representing the day of the week (i.e from 0 to 6) instead of returning a name such as Sunday or Monday in such a way that. This means that, if it is Sunday, the method returns 0; and if it is Monday, the method returns 1, and so on.
Same here also, the getMonth() method returns the number of months (i.e from 0 to 11) instead of the name of the month. Just like above, 0 represents the first month of the year, so if it is January the method returns 0, not 1; and if it is August, the method returns 7 and not 8.
More so, the Date object provides methods like getHours(), getMinutes(), getSeconds(), getTimezoneOffset() and so on. They are used to extract the time components from the Date object.
var d = new Date();
// Extracting time part
alert(d.getHours()); // Display the number of hours into the day (0-23)
alert(d.getMinutes()); // Display the number of minutes into the hour (0-59)
alert(d.getSeconds()); // Display the seconds into the minute (0-59)
alert(d.getMilliseconds()); // Display the number of milliseconds into second (0-999)
alert(d.getTime()); // Display the number of milliseconds since 1/1/1970
alert(d.getTimezoneOffset()); // Display the time-zone offset (from Greenwich Mean Time) in minutes
The method getHours() returns the number of hours into the day (i.e. from 0 to 23) according to the 24-hour clock. Therefore, when it is midnight, the getHours() method returns 0; and when it is 3:00 P.M., it returns 15.
Note: The Date objects also have methods to obtain the UTC components, such as getUTCDate(), getUTCHour(), getUTCMinutes(), and so on.
More so, to retrieve date and time values, you can set or modify these values using the JavaScript. This approach is most often used in a program that requires you to change the value of a date object from one particular date or time to another.
The Date object also provides methods such as setFullYear(), setMonth(), and setDate() methods to set the year, month, and date components of the Date object respectively.
In the example below, we have used setFullYear() method to change the current date stored in a variable ahead of two years in the future.+ 2).
var d = new Date();
d.setFullYear(d.getFullYear() + 2);
alert(d); // Display future date
However, you can use the setMonth() method to set or modify the month part of a Date object.
var d = new Date(); // Current date and time
d.setMonth(0); // Sets month to 0, January
document.write(d);
It requires an integer value from 0 to 11. But, if you set the value of the month greater than 11, the year value of the date object will increment.
In other words, a value of 12 produces results in the year value that increases by 1, and the month value set to 0, as illustrated in the example below:
var d = new Date(2022, 7, 15); // August 15, 2022
d.setMonth(12); // Sets month to 12, new date will be August 15, 2023
document.write(d);
Also, the date part of the date object can be modified, like this;
var d = new Date(2022, 7, 1); // August 1, 2022
d.setDate(15); // Sets date to 15, new date will be August 15, 2022
document.write(d);
The setDate() method takes an integer value starting from 1 to 31. however, if you pass the values greater than the number of days in the month, it will cause an increment in the month. Take a look at the example:
var d = new Date(2022, 7, 15); // June 24, 2018
d.setDate(36); // Sets day to 36, new date will be Sep 5, 2022
document.write(d);
Methods for setting the time values are straightforward. In the Date object, setHours(), setMinutes(), setSeconds(), setMilliseconds() can be used to set the hour, minutes, seconds, and milliseconds part respectively.
All the methods in the Date object take integer values as parameters. For instance, Hours range from 0 to 23; Minutes and seconds range from 0 to 59; milliseconds range from 0 to 999. This is illustrated in the example below:
var d = new Date(2022, 7, 15); // Aug 15, 2022 00:00:00
d.setHours(8);
d.setMinutes(30);
d.setSeconds(45);
d.setMilliseconds(600);
document.write(d);