JavaScript function to get date in mmddyyyy hhmmss ampm format

Below JavaScript function getdatetime() will return the date string in mm/dd/yyyy hhmmss ampm format. You need to pass date as parameter that need to be returned in the format mm/dd/yyyy hhmmss ampm. If you want current date in the format then you can simple call the function as getdatetime(new Date());

Example

JavaScript Function

function getdatetime(dt) { var res = ""; res += formatdigits(dt.getMonth() + 1); res += "/"; res += formatdigits(dt.getDate()); res += "/"; res += formatdigits(dt.getFullYear()); res += " "; res += formatdigits(dt.getHours() > 12 ? dt.getHours() - 12 : dt.getHours()); res += ":"; res += formatdigits(dt.getMinutes()); res += ":"; res += formatdigits(dt.getSeconds()); res += " " + dt.getHours() > 11 ? " PM" : " AM"; return res; } function formatdigits(val) { val = val.toString(); return val.length == 1 ? "0" + val : val; }

Calling function:

var dtformated = getdatetime(new Date()); $("#divdatetime").html(dtformated);

Source code:

<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title></title> <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script> <script> function getdatetime(dt) { var res = ""; res += formatdigits(dt.getMonth() + 1); res += "/"; res += formatdigits(dt.getDate()); res += "/"; res += formatdigits(dt.getFullYear()); res += " "; res += formatdigits(dt.getHours() > 12 ? dt.getHours() - 12 : dt.getHours()); res += ":"; res += formatdigits(dt.getMinutes()); res += ":"; res += formatdigits(dt.getSeconds()); res += " " + dt.getHours() > 11 ? " PM" : " AM"; return res; } function formatdigits(val) { val = val.toString(); return val.length == 1 ? "0" + val : val; } $(document).ready(function () { var dtformated = getdatetime(new Date()); $("#divdatetime").html(dtformated); }); </script> </head> <body> <div id="divdatetime"> </div> </body> </html>