You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

AngularJS Material Datepicker日期格式修改:如何仅显示YYYY-MM-DD?

解决AngularJS Material Datepicker日期格式问题

先修正模板中的绑定错误

你当前的HTML代码里,md-datepicker同时写了两个ng-model:

<md-datepicker ng-model="user.next_class" ng-model="myDate" ...></md-datepicker>

这会导致数据绑定冲突,必须删除其中一个(比如保留ng-model="myDate"),确保数据能正确绑定到你期望的变量上。


方法1:原生JavaScript格式化(无需第三方库)

如果不想引入额外依赖,可以自己写个简单的格式化函数,在提交数据时处理日期:

在控制器中添加这个格式化函数:

$scope.formatToYMD = function(date) {
  if (!date) return '';
  const year = date.getFullYear();
  // 月份从0开始,需+1后补零保证两位数
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
};

提交数据时调用该函数处理:

// 假设你的提交函数是submitForm
$scope.submitForm = function() {
  const formattedDate = $scope.formatToYMD($scope.myDate);
  // 用formattedDate代替原Date对象提交到后端
  console.log('格式化后的日期:', formattedDate); // 输出示例:2018-05-23
};

方法2:使用Moment.js格式化(符合你的需求)

如果你已经引入了Moment.js,处理起来会更简洁灵活:

方式A:提交时直接格式化

$scope.submitForm = function() {
  const formattedDate = moment($scope.myDate).format('YYYY-MM-DD');
  console.log('格式化后的日期:', formattedDate);
  // 将formattedDate作为提交参数即可
};

方式B:自定义AngularJS过滤器(模板/控制器通用)

注册一个自定义过滤器,这样在模板里也能直接显示格式化后的日期:

angular.module('yourAppModuleName')
  .filter('ymdDate', function() {
    return function(date) {
      if (!date) return '';
      return moment(date).format('YYYY-MM-DD');
    };
  });

模板中使用过滤器显示:

<p>选中的日期:{{ myDate | ymdDate }}</p>

控制器中注入过滤器使用:

$scope.submitForm = function() {
  const ymdDateFilter = $filter('ymdDate');
  const formattedDate = ymdDateFilter($scope.myDate);
  // 提交格式化后的日期
};

方法3:使用AngularJS原生date过滤器(轻量方案)

AngularJS内置了date过滤器,也能满足基础格式化需求:

模板中直接显示格式化结果:

<p>选中的日期:{{ myDate | date:'yyyy-MM-dd' }}</p>

控制器中通过$filter调用:

$scope.submitForm = function() {
  const formattedDate = $filter('date')($scope.myDate, 'yyyy-MM-dd');
  console.log(formattedDate);
};

注意:原生过滤器依赖AngularJS的本地化配置,若项目有国际化需求可能需要额外调整,但针对简单的YYYY-MM-DD格式完全够用。

内容的提问来源于stack exchange,提问作者J. Perk

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 06:17:02