angular - 如何在时刻 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 来实现这一点需要您的帮助。
解决方案
使用 moment 你可以通过使用它来实现它
moment(datavalue).format('ddd DD [of] MMMM')
我认为这将解决您的问题。
推荐阅读
- mongodb - Mongoose 使用嵌套数组更新文档中的整个对象
- go - 如何读取文件的特定行数?
- git - SSH - 从配置存储库获取配置时身份验证失败
- c# - Confluent Kafka Dotnet Kerberos 支持 Dockerfile(SASL 机制 GSSAPI 没有提供者)
- python - 使用pickle.load()时python3退出没有任何错误
- vue.js - 如何将 Phylotree.js 添加到 nuxt?
- mysql - 如何删除特定列上的重复项?
- jquery - 在函数结束时重复函数
- java - Maven - 在编译时发现类类型
- python - 如何平滑 z 值并减少其在 python 中的变化?