Menu ▼



Posted By :
avatarmrkraju
Total Views : 168

JavaScript function to get date in mmddyyyy format

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

Example:

Javascript Function:

function getdate(dt) {
    var res = "";
    if ((dt.getMonth() + 1).toString().length < 2)
        res += "0" + (dt.getMonth() + 1).toString();
    else
        res += (dt.getMonth() + 1).toString();
    res += "/";
    if (dt.getDate().toString().length < 2)
        res += "0" + dt.getDate().toString();
    else
        res += dt.getDate().toString();
    res += "/" + dt.getFullYear().toString();
    return res;
}

Calling function:

var dtformated = getdate(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 getdate(dt) {
            var res = "";
            if ((dt.getMonth() + 1).toString().length < 2)
                res += "0" + (dt.getMonth() + 1).toString();
            else
                res += (dt.getMonth() + 1).toString();
            res += "/";
            if (dt.getDate().toString().length < 2)
                res += "0" + dt.getDate().toString();
            else
                res += dt.getDate().toString();
            res += "/" + dt.getFullYear().toString();
            return res;
        }
        $(document).ready(function () {
            var dtformated = getdate(new Date());
            $("#divdatetime").html(dtformated);
        });
    </script>
</head>
<body>
    <div id="divdatetime">
    </div>
</body>
</html>






comments powered by Disqus


Search dotnetlearners.com