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());
ExampleJavaScript 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>
Useful Tools
Online Code Editor and Compiler
HTML Minifier
Online HTML Compiler/Preivew
Word Count Tool
Replace Text/Word tool
Latest Blogs
How to check if a canvas is empty or blank
Maintain div or panel scroll position after postback in asp.net update panel
Draggable button using jquery ui
Get total number of tables, views, stored procedures and functions count and names in sql server
JavaScript function to get date in mmddyyyy hhmmss ampm forma