This below blog post will help you to find the current date and time in JavaScript and we are also going to also explain to get date and time in your formats like Y-m-d and H:i:s formats.
Get Current Date And Time in JavaScript
By Using Date() function in JavaScript ,we can create an object with current date and time and This provides output in UTC timezone.
var current_date = new Date();
-
Current Date in JavaScript
By the help of below script in javaScript we can find out the current date in “y-m-d” format.
var current_date = new Date(); var date = current_date.getFullYear()+'-'+(current_date.getMonth()+1)+'-'+current_date.getDate();
getFullYear() – this function provides current year like 2020.
getMonth() – this function provides current month values 0-11. Where 0 for Jan and 11 for Dec. So added +1 to get desired result.
getDate() – this function provides the day of the month values 1-31.
-
Current Time in JavaScript
Through the below script we can find out the current time using JavaScript in “H:i:s” format.
var current_date= new Date(); var time = current_date.getHours() + ":" + current_date.getMinutes() + ":" + current_date.getSeconds();
getHours() – This function provides current hour between 0-23.
getMinutes() – This function provides current minutes between 0-59.
getSeconds() – This function provides current seconds between 0-59.
-
Getting Both Current Date & Time in JavaScript
Use the below script to get the current date and time using JavaScript in “Y-m-d H:i:s” format.
We can combine the output of the above JavaScript code in one variable and get the desired outpout like as below:-
var current_date= new Date(); var date = current_date.getFullYear()+'-'+(current_date.getMonth()+1)+'-'+current_date.getDate(); var time = current_date.getHours() + ":" + current_date.getMinutes() + ":" + current_date.getSeconds(); var date_Time = date+' '+time;
After executing the above script you will get the output like below:-
2020-2-9 13:21:9