Pages

Friday, 14 March 2014

How to Convert AM PM Time to 24 Hour Time jQuery

How to Convert AM PM Time to 24 Hour Time jQuery
 
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>jQuery Convert AM / PM time to 24 hours time</title>
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.js"></script>
    <script type="text/javascript">
        $(function () {
            $('#btnConvert').click(function () {
                var time = $("#txttime").val();
                var hrs = Number(time.match(/^(\d+)/)[1]);
                var mnts = Number(time.match(/:(\d+)/)[1]);
                var format = time.match(/\s(.*)$/)[1];
                if (format == "PM" && hrs < 12) hrs = hrs + 12;
                if (format == "AM" && hrs == 12) hrs = hrs - 12;
                var hours = hrs.toString();
                var minutes = mnts.toString();
                if (hrs < 10) hours = "0" + hours;
                if (mnts < 10) minutes = "0" + minutes;
                alert(hours + ":" + minutes);
            })
        })
    </script>
</head>
<body>
    <table>
        <tr>
            <td><b>Enter Time:</b></td>
            <td>
                <input type="text" id="txttime" value="12:00 PM" /></td>
        </tr>
        <tr>
            <td></td>
            <td>
                <input type="button" id="btnConvert" value="Convert to AM/PM" /></td>
        </tr>
    </table>
</body>
</html>

Enter Time:


No comments:

Post a Comment