How to get current Date Time in JavaScript: In Easy Way
In this tutorial, we are going to see How to get the current Date time in JavaScript. We are going to use Javascript library function Date(). We will take an example to see how to format javascript date to MySQL format Y-m-d
and H:i:s
format.
By default, Javascript Date() function returns a current date time obj in UTC format/timezone.
Creating current DateTime Object using new Keyword.
let today= new Date();
Getting the current date from the date object in Y-m-d format.
let date = today.getFullYear()+'-'+(today.getMonth()+1)+'-'+today.getDate();
Note: JavaScript date object Month index will start from 0 so to get real Date time we have to add +1 in it.
Getting current time from Date object in H:i:s format
let time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
Getting Complete DateTime in Y-m-d H:i:s format from date object
let date = today.getFullYear()+'-'+(today.getMonth()+1)+'-'+today.getDate(); let time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds(); let dateTime = date+' '+time; console.log(dateTime);