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

Angular日期选择器如何设置发送日期为DD.MM.YY格式?

Fixing Date Format for Angular Material Datepicker (Display vs. Send)

Hey there! I see you're working with Angular Material's Datepicker and need to keep the display format as LL but send dates in DD.MM.YY (like 24.07.19) instead of that messy default string output. Let's break down how to fix this quickly.

The Core Issue

Right now, your [(ngModel)]="search" is binding to a Date or Moment object (depending on your adapter setup). When you send this object directly, JavaScript converts it to that long, unreadable string you're seeing. The fix is simple: convert this object to your desired string format right before sending the request.

Solution 1: Use Moment.js (Since You're Already Using MomentDateAdapter)

Since you’ve set up MomentDateAdapter, you already have Moment.js in your project—perfect! Just format the date object when you’re ready to send it.

Update Your applyFilter() Method

Modify your TypeScript code to format the date inside the applyFilter function:

import * as moment from 'moment'; // Ensure this import exists at the top of your component

// ...

applyFilter() {
  if (this.search) {
    // Format the Moment/Date object to DD.MM.YY
    const formattedDate = moment(this.search).format('DD.MM.YY');
    
    // Now use formattedDate in your API request or wherever you need it
    console.log('Date to send:', formattedDate); // Outputs "24.07.19"
  }
}

Solution 2: Native JavaScript (No Moment.js)

If you prefer not to rely on Moment.js for formatting, you can write a simple helper function to convert a Date object to your desired format:

Add a Date Formatting Helper

Add this function to your component:

private formatToDDMMYY(date: Date): string {
  const day = String(date.getDate()).padStart(2, '0');
  const month = String(date.getMonth() + 1).padStart(2, '0'); // Months are 0-indexed!
  const year = String(date.getFullYear()).slice(-2); // Grab last 2 digits of the year
  
  return `${day}.${month}.${year}`;
}

Use It in applyFilter()

applyFilter() {
  if (this.search) {
    const formattedDate = this.formatToDDMMYY(this.search);
    // Send formattedDate instead of the raw date object
  }
}

Important Note: Keep Display Format Intact

Your existing MAT_DATE_FORMATS setup is correct for keeping the Datepicker display as LL—don’t change that! The key is to separate the display format (handled by the Datepicker config) from the send format (handled by your formatting logic right before sending the request).

内容的提问来源于stack exchange,提问作者user11855532

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 06:34:18