【问题标题】:How fix max number day in Month with Angular?如何使用 Angular 修复每月的最大天数?
【发布时间】:2020-06-05 17:07:10
【问题描述】:

我有一个带有 datepicker 的日期函数(使用 Angular 8),但我有一个问题。例如,当我输入 36/04/2020 时,它会以 05/06/2020 的日期保存在数据库中。 我希望当天数超过一个月的天数时,它会在最后一天返回给我(例如,在我的情况下,必须输入 30/04/2020)。 如何解决这个问题,谢谢?

代码.ts:

import { NativeDateAdapter, DateAdapter, MAT_DATE_FORMATS, MatDateFormats } from "@angular/material";

    export class AppDateAdapter extends NativeDateAdapter {

        parse(value: any): Date | null {
            if ((typeof value === 'string') && (value.indexOf('/') > -1)) {
              const str = value.split('/');
              const year = Number(str[2]);
              const month = Number(str[1]) - 1;
              const date = Number(str[0]);
              return new Date(Date.UTC(year, month, date));
              ;
            }
            const timestamp = typeof value === 'number' ? value : Date.parse(value);
            return isNaN(timestamp) ? null : new Date(timestamp);
          }

          createDate(year: number, month: number, date: number): Date {
            return new Date(Date.UTC(year, month, date));
          }

          format(date: Date, displayFormat: Object): string {
            if (displayFormat === 'input') {
              let day: string = date.getUTCDate().toString();
              day = +day < 10 ? '0' + day : day;
              let month: string = (date.getUTCMonth() + 1).toString();
              month = +month < 10 ? '0' + month : month;
              let year = date.getUTCFullYear();
              return `${day}/${month}/${year}`;

            }
            // new Date(date.toDateString()).getUTCDate(); 
            return date.toDateString();

          }

       private _to2digit(n: number) {
           return (n);
           //return ('00' + n).slice(-2);
       } 
    }

    export const APP_DATE_FORMATS =
    {
       parse: {
           dateInput: {month: 'short', year: 'numeric', day: 'numeric'}
       },
       display: {
           // dateInput: { month: 'short', year: 'numeric', day: 'numeric' },
           dateInput: 'input',
           // monthYearLabel: { month: 'short', year: 'numeric', day: 'numeric' },
           monthYearLabel: 'inputMonth',
           dateA11yLabel: {year: 'numeric', month: 'long', day: 'numeric'},
           monthYearA11yLabel: {year: 'numeric', month: 'long'},
       }
    }

【问题讨论】:

    标签: html angular date datepicker


    【解决方案1】:

    这将为您提供本月的最后一天 =>

    const day = new Date(2020, month + 1, 0)
    

    然后获取日期

    day.getDate() it will return 31 for January
    

    最后比较

    inputValue = inputValue > day.getDate() ? day.getDate() : inputValue
    

    【讨论】:

      猜你喜欢
      • 2019-01-20
      • 1970-01-01
      • 2020-03-28
      • 1970-01-01
      • 2022-01-13
      • 2015-10-13
      • 2018-07-31
      • 1970-01-01
      • 2020-10-16
      相关资源
      最近更新 更多