首页 > 解决方案 > 如何在时刻 js 中格式化日期

问题描述

我们如何从时刻 js 自定义日期?我只想显示例如:本月的星期四 10。我们如何使用 moment 或 pipe 来实现这一点需要您的帮助。

app.component.html

<h2>{{ dateCtr.value | date }}</h2>

app.component.ts

import { Component } from '@angular/core';
import {FormControl} from '@angular/forms';
import {MomentDateAdapter, MAT_MOMENT_DATE_ADAPTER_OPTIONS} from '@angular/material-moment-adapter';
import {DateAdapter, MAT_DATE_FORMATS, MAT_DATE_LOCALE} from '@angular/material/core';

import _moment from 'moment';
// tslint:disable-next-line:no-duplicate-imports
import {default as _rollupMoment} from 'moment';

const moment = _rollupMoment || _moment;

// See the Moment.js docs for the meaning of these formats:
// https://momentjs.com/docs/#/displaying/format/
export const MY_FORMATS = {
  parse: {
    dateInput: 'LL',
  },
  display: {
    dateInput: 'LL',
    monthYearLabel: 'MMM YYYY',
    dateA11yLabel: 'LL',
    monthYearA11yLabel: 'MMMM YYYY',
  },
};

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ],
  providers: [
    // `MomentDateAdapter` can be automatically provided by importing `MomentDateModule` in your
    // application's root module. We provide it at the component level here, due to limitations of
    // our example generation script.
    {
      provide: DateAdapter,
      useClass: MomentDateAdapter,
      deps: [MAT_DATE_LOCALE, MAT_MOMENT_DATE_ADAPTER_OPTIONS]
    },

    {provide: MAT_DATE_FORMATS, useValue: MY_FORMATS},
  ],
})

export class AppComponent  {

  dateCtr = new FormControl(moment());

  incrementDate(){
  this.dateCtr.setValue(moment(this.dateCtr.value).add(1, 'days').format());
 }

  decrementDate(){
  this.dateCtr.setValue(moment(this.dateCtr.value).subtract(1, 'days').format());
 }

}

管道.ts

import { Pipe, PipeTransform } from '@angular/core';
import { DatePipe } from '@angular/common';

@Pipe({ name: 'mypipe' })
export class Mypipe implements PipeTransform {
  // adding a default value in case you don't want to pass the format then 'yyyy-MM-dd' will be used
  transform(date: Date | string, day: number, format: string = 'yyyy-MM-dd'): string {
    date = new Date(date);  // if orginal type was a string
    date.setDate(date.getDate() - day);
    return new DatePipe('en-US').transform(date, format);
  }
}

我们如何从时刻 js 自定义日期?我只想显示例如:本月的星期四 10。我们如何使用 moment 或 pipe 来实现这一点需要您的帮助。

标签: angularpipemomentjs

解决方案


使用 moment 你可以通过使用它来实现它

moment(datavalue).format('ddd DD [of] MMMM')

我认为这将解决您的问题。


推荐阅读