How To Get Current Date And Time In JavaScript And Setting Date Format

This is a quick post will help you to get current date and time in javascript and setting required date format, As you know there is no direct function in javascript to change date format As you can change in PHP. But you can separately get year, month, day, hour, minute and second in javascript and then concatenate in required format. See below example



How To Get Current Date And Time In JavaScript

JavaScript Date object help you to work with dates. Simply Use new Date() to create a new object for current date and time.

var today = new Date();

Setting date format in d-m-Y

var curDate = today.getDate()+'-'+(today.getMonth()+1)+'-'+today.getFullYear();

Setting date format in Y/m/d

var curDate = today.getFullYear()+'/'+(today.getMonth()+1)+'/'+today.getDate();

By using above parameter you can set any data format in javascript like d-m-Y, Y-m-d, m-d-Y etc.

Getting current time from Date object in h:i:s format and concatenate with current date.

var curTime = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();

Getting current date and time in javascript like format (d-m-Y h:i:s)

var curDateTime = today.getDate()+'-'+(today.getMonth()+1)+'-'+today.getFullYear()+" ".today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
alert(curDateTime);
console.log(curDateTime);