Display time and date in JavaScript
date and time in javascript, today we are going to talk about date and time in javascript. The javascript language provides a wide range of functions related to the date and time. Today we are going to talk about an object called date in javascript by which we can get all the time data.
Functions used with date and time javascript
- View the year getFullYear().
- month view getMonth() fetches the month from 0 to 11.
- Today's view getDate().
- View getHours().
- View getMinutes() minutes.
- Displays the seconds getSeconds().
- Displays in milliseconds getMilliseconds().
- Displays the seconds from 1970 to now getTime().
- Show the day starting from the first day of the week getDay().
new Date() function in JavaScript
This function creates a Date object with the current date and time.
let now = new Date();
alert( now );
View the current year
var date = new Date();
var time = document.getElementById("time");
time.innerHTML = date.getFullYear();
Show current month
var date = new Date();
var time = document.getElementById("time");
time.innerHTML = date.getMonth();
When executing this code, it will display the month from (0 to 11), that is, if we are in the fifth month, it will display the number 4, but if we want to display it systematically, we put +1 after the function.
time.innerHTML = date.getMonth()+1;
But sometimes this method will not work. The data type we want to get must be converted from string to number. We explained this previously via parseInt or Float to become.
time.innerHTML = parseInt( date.getMonth())+1;
Show current day
time.innerHTML = date.getDate();
Show current hours
time.innerHTML = date.getHours();
Show seconds
time.innerHTML = date.getSeconds();
Show minutes
time.innerHTML = date.getMinutes();
Displays the day as a number starting from the first day of the week
time.innerHTML = date.getDay();
To display the milliseconds from 1970 to the present
time.innerHTML = date.getTime();
Programmers are not advised to use the getYear() method because it has become obsolete and fetches the year in two digits sometimes. Rather, it is recommended to use getFullYear(). There are similar ones in UTC where it returns the day, month, year, etc. in the timezone UTF+0:
- getUTCFullYear().
- getUTCMonth().
- getUTCDay().
Put the word "UTC" after "get" and you will find the appropriate instance.
Automatic correction system to deal with time
AutoCorrect on Date objects is very useful. We can set irrational Date values (such as the fiftieth of this month) and the object will modify them by itself.
let date = new Date(2022, 0, 32);
alert(date);