If you are searching for JavaScript code to convert the current date format to MM/dd/yyyy HH:mm:ss format, you have come to the right place.
function formatDate(date) {
var d = new Date(date),
month = '' + (d.getMonth() + 1),
day = '' + d.getDate(),
year = d.getFullYear();
hour = '' + d.getHours();
min = '' + d.getMinutes();
if (month.length < 2) month = '0' + month;
if (day.length < 2) day = '0' + day;
if (hour.length < 2) hour = '0' + hour;
if (min.length < 2) min = '0' + min;
var result = [year, month, day].join('-');
return result + " " + hour + ":" + min;
}
In the above JavaScript function, you just need to pass the date object, and it will return the desired date format.
As you can see in the code, it’s very simple. You can always format a date by extracting the parts of the date object and combining them using strings.
You can also write a generic function so that you can convert the date object to any format like below function.
function formatDate(datetimeObj, format) {
var curr_date = datetimeObj.getDate();
var curr_month = datetimeObj.getMonth();
curr_month = curr_month + 1;
var curr_year = datetimeObj.getFullYear();
var curr_min = datetimeObj.getMinutes();
var curr_hr = datetimeObj.getHours();
var curr_sc = datetimeObj.getSeconds();
if (curr_month.toString().length == 1)
curr_month = '0' + curr_month;
if (curr_date.toString().length == 1)
curr_date = '0' + curr_date;
if (curr_hr.toString().length == 1)
curr_hr = '0' + curr_hr;
if (curr_min.toString().length == 1)
curr_min = '0' + curr_min;
if (format == 1)//dd-mm-yyyy
{
return curr_date + "-" + curr_month + "-" + curr_year;
}
else if (format == 2)//yyyy-mm-dd
{
return curr_year + "-" + curr_month + "-" + curr_date;
}
else if (format == 3)//dd/mm/yyyy
{
return curr_date + "/" + curr_month + "/" + curr_year;
}
else if (format == 4)// MM/dd/yyyy HH:mm:ss
{
return curr_month + "/" + curr_date + "/" + curr_year + " " + curr_hr + ":" + curr_min + ":" + curr_sc;
}
}
This JavaScript function, formatDate, takes a date object (datetimeObj) and a format code (format) as input, and returns the date in the specified format. Here's how it works:
It checks the format code provided:
Above function provides a flexible way to format a given date object according to different date format options.