JavaScript Date Time into 12 Hour(AM/PM) Time format. A sample implementation in AngularJS

Sample Code: 

var date = new Date(time);
var hours = date.getHours();
var minutes = date.getMinutes();
var ampm = hours >= 12 ? 'pm' : 'am'; hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
minutes = minutes < 10 ? '0' + minutes : minutes;
var strTime = hours + ':' + minutes + ' ' + ampm; return strTime; 

Demo:

Here is a sample implementation to convert JavaScript Date Time into 12 Hour(AM/PM) time format,

Convert Time into 12 Hour(AM/PM) Time Format- AngularJS
Formated Time: {{data.time | formatTime}}

Example:
<html>
<head>
    <title>Convert Time into 12 Hour(AM/PM) Time Format- AngularJS</title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
</head>
<body>
    <div ng-app="myApp" ng-controller="myController">
        <div style="">
            <input id="updateval" type="text" placeholder="Click Load Time Button.." style="width:500px; height:30px; padding: 5px; margin: 15px 0;"
                ng-model="data.time">
            <button ng-click="loadTime()">Load Time</button>
        </div>
        <div><span><strong>Formated Time: </strong></span><span>{{data.time | formatTime}}</span></div>
    </div>
    </div>
    <script>
        var myApp = angular.module("myApp", []);
        myApp
        .filter('formatTime', function () {
           return function (time) {
             var date = new Date(time);
             var hours = date.getHours();
             var minutes = date.getMinutes();
             var ampm = hours >= 12 ? 'pm' : 'am';
             hours = hours % 12;
             hours = hours ? hours : 12; // the hour '0' should be '12'
             minutes = minutes < 10 ? '0' + minutes : minutes;
             var strTime = hours + ':' + minutes + ' ' + ampm;
             return strTime;
           };
         })
         .controller('myController', function($scope) {
           $scope.data = {
              time: 'Wed Dec 14 2016 16:14:00 GMT+0530 (India Standard Time)',
           };
           $scope.loadTime = function(){
             $scope.data = {
              time: new Date(),
           };
           }
        });
     </script>
</body>
</html>
Category: