programing

Angulargular Js:지정된 월 번호의 월 이름 표시

oldcodes 2023. 2. 28. 23:45
반응형

Angulargular Js:지정된 월 번호의 월 이름 표시

월은 숫자(1, 2, 3, ...)로 되어 있어 대응하는 이름을 표시하고 싶습니다.이거 어떻게 해?

{{ date_expression | date[:format] }}

https://docs.angularjs.org/api/ng/filter/date 에서 문서를 참조해 주세요.원하는 형식이 표시됩니다.

{{date_expression | date:'MMMM'}}

문서에서:

'MMMM': Month in year (January-December)

월 인덱스가 있는 경우 자체 필터를 만들 수 있습니다.

myApp.filter('monthName', [function() {
    return function (monthNumber) { //1 = January
        var monthNames = [ 'January', 'February', 'March', 'April', 'May', 'June',
            'July', 'August', 'September', 'October', 'November', 'December' ];
        return monthNames[monthNumber - 1];
    }
}]);

그런 다음 템플릿에서 다음을 수행합니다.

{{date_expression | monthName}}

형식 문자열은 몇 개월 동안 다음 요소로 구성될 수 있습니다.

MMM' :(1~ - 'MM' : 1월~12월){{D_V | date:'yyyy-MMMM-dd'}}

MM' : 12월 - 'MM' : 월 ( 1 ~12월) -{{D_V | date:'yyyy-MMM-dd'}}

: - 'MM' : 년월, 딩01 ( 01-12) -{{D_V | date:'yyyy-MM-dd'}}

: (1~12) - 'M' : ( (1~12) -{{D_V | date:'yyyy-M-dd'}}

각도 JS 날짜 필터에서 자세히 알아보기

월은 날짜 객체가 아닌 정수 값으로 알고 있습니다. 로, " "/" ( " ) " " " " ( " ) " " " ( " ) " " " " ( " ) " " " " " ( " ) " " " " " " ( " ) " " " " " " " " " " " " " " " ( " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " "Date★★★★★★ 。

따라서 해당 달의 정수 값을 필터가 인식하는 값으로 변환해야 합니다.을 취하여 로 만든 후 더미를 수 .Date그 필터에 합니다.Date.

컨트롤러:

angular.module('demo', [])
  .controller('DemoCtrl', function($scope) {
      // here's the original value
      $scope.month = 0; // 0 for january, 11 for december

      // watch for changes to the value of month. turn it into a new date object that angular can bind and filter in the view
      $scope.$watch('month', function(val) {
        // note: if you are expecting the month value to be one-indexed, you'll need to subtract 1 from val to make it zero-indexed as Date expects
        $scope.date = new Date(2014, val);
      });
    });

표시:

{{ date | date:'MMMM' }}

예를 참조해 주세요.

하나의 은 '보다 낫다'를 입니다.$filter직접 서비스를 제공할 수 있습니다.기본적으로 동일한 작업을 수행하며 뷰가 아닌 컨트롤러에서 값을 포맷합니다.

컨트롤러:

// Code goes here
angular.module('demo', [])
  .controller('DemoCtrl', function($scope, $filter) {
      // here's the original value
      $scope.month = 0;

      // watch for changes to the value of month, and then format it directly
      $scope.$watch('month', function(val) {
        $scope.date = $filter('date')(new Date(2014, val), 'MMMM');
      });
    });

표시:

{{ date }}

대체 예

답을 찾았어요.문제는 간단하다.mysql date time을 javascript date time으로 변환해야 합니다.그러면 javascript로 포맷할 수 있습니다.

포맷은 다음과 같습니다:2008-04-25 00:00:00

  app.filter('format', function () {
          return function (item) {
               var t = item.split(/[- :]/);
           var d = new Date(t[0], t[1]-1, t[2], t[3], t[4], t[5]);
           var time=d.getTime();                 
                   return time;
          };
        });

mysql을 javascript로 변환하고 밀리초로 변환한 후 필터를 적용했습니다.이것은 효율적이지 않을 수 있습니다.그것은 아주 잘 작동한다.이게 도움이 됐으면 좋겠네요.

그래서 내 html:

<li  ng-repeat="x in names">
                <div class="date">
                <span class="day">{{ x.created_at | format | date:'d'}}</span>
                <span class="month">{{ x.created_at | format | date:'MMM'}}</span>
                </div>
                <p><a href="#">{{ x.study_description | makeUppercase}}</a></p>
            </li>

잘 되고 있어요.@니샨스의 대답은 애매모호하다.어떤 사람들은 잘 될 것 같아서 상향투표를 했어요.브라우저 도구에 따라 날짜 형식 지원도 달라집니다.

사실, 가장 간단한 방법은 여기에 게시된 두 개의 다른 답변을 조합하는 것입니다.필터에서 필터를 사용하여 변환 및 현재 언어 집합의 월 이름 표시:

app.filter('monthname',['$filter',function($filter){
    return function(month) {
      return $filter("date")(new Date(0,month),'MMMM');
    }
}]);

이제 이 방법을 사용할 수 있습니다.{{ 3 | monthname }}

이것이 없으면 원래 필터는{{ 3 | date:'MMMM' }}예상대로 되지 않을 것이다Date인수로 입력하고 숫자는 입력하지 않습니다.

MM을 사용하여 월을 숫자로 가져옵니다.

{{message.end_date | date : "dd-MM-y"}} 

그러면 2017년 12월 1일에 결과가 표시됩니다.

angular.module('demo', [])
  .controller('DemoCtrl', ['$scope', '$filter', 'lodash', function($scope, $filter, _) {
    $scope.monthNames = _.range(12).map(function(m) {
        return $filter("date")(new Date(0, m), 'MMMM'); }); 
    }]);

lodash를 사용하여 0부터 11까지의 번호 범위를 파악하고 있지만, 다른 방법으로 쉽게 목록을 얻을 수 있습니다.

Angular's filters.js에 있는 날짜 필터의 소스 코드를 들여다보니 Angular가 다음 달에 목록을 저장하는 것을 알 수 있었습니다.$locale.DATETIME_FORMATS.MONTH매우 효율적인 필터를 만들기 위해 사용할 수 있습니다.

var app = angular.module("app", []); 

app.filter("month", function($locale) {
    return function(month) {
        return $locale.DATETIME_FORMATS.MONTH[month];
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
    <p ng-repeat="num in [0,1,2,3,4,5,6,7,8,9,10,11]">
       <span ng-bind="$index + 1"></span>: 
       <span ng-bind="$index | month"></span>
    </p>
</div>

또는 필터를 사용하지 않고 대신 컨트롤러에 넣습니다.

var app = angular.module("app", []); 

app.controller("ctrl", function($scope, $locale) {
    $scope.months = $locale.DATETIME_FORMATS.MONTH;
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
    <p ng-repeat="num in [0,1,2,3,4,5,6,7,8,9,10,11]">
       <span ng-bind="$index + 1"></span>: 
       <span ng-bind="months[$index]"></span>
    </p>
</div>

아니면 지시사항으로도요오버킬이 될 수도 있지만 HTML은 확실히 예뻐 보인다(내 눈에는).

var app = angular.module("app", []);

app.directive("month", function($locale) {
    return {
        restrict: "A",
        link: function ($scope, elem, atrs) {
            $scope.$watch(atrs.month, function(month) {
                elem.text($locale.DATETIME_FORMATS.MONTH[month]);
            });
        }
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
    <p ng-repeat="num in [0,1,2,3,4,5,6,7,8,9,10,11]">
       <span ng-bind="$index + 1"></span>: 
       <span month="$index"></span>
    </p>
</div>

언급URL : https://stackoverflow.com/questions/21480359/angularjs-show-name-of-the-month-given-the-month-number

반응형