给定当前日期:
var myDate = new Date()
我需要以这种方式格式化当前日期:
2014年6月10日
我也必须实现本地化,因此结果应为 2014年6月10日,但对于它,结果应为 10 GIU 2014 。
实施它的正确方法是什么?
感谢支持
要获得当前日期,您应该在您的.ts文件中声明一个变量,如
public today = Date.now();
然后在html文件中使用带有日期管的
的日期管道中的变量{{today | date }}
我还必须实施本地化,因此为EN而言,结果应该是 2014年6月10日,但结果应为10 GIU 2014。
对于更改时区,请查看Angular Date Pipe
在模块TS文件中
import localeitCH from '@angular/common/locales/it-CH';
registerLocaleData(localeitCH);
providers: [
{provide: LOCALE_ID, useValue: 'it-CH' } ], //you can try out the other locales as per the need
在html文件中
<!-- {{today | date:'dd MMM yyyy'}} -->
{{today | date:'dd MMM yyyy':'':'en-US' | titlecase }} <!-- en-US is the previous(angular) default locale -->
{{today | date:'dd MMM yyyy' | titlecase }} <!-- have changed to the it-CH , hence need not to mention here-->
<!--Have used titlecase pipe to display text in title case -->
在TS文件中
import { DatePipe,TitleCasePipe } from '@angular/common';
today = Date.now(); // Inside the component class
希望这会有所帮助!
注意:不要混淆,因为两种情况下两者都给出了相同的结果APR [4月,APRILE],请尝试添加m以查看月名=> mmmm而不是MMM,名称
myDate.toLocaleDateString('en-EN', { year: 'numeric', month: 'short', day: '2-digit' });
myDate.toLocaleDateString('it-IT', { year: 'numeric', month: 'short', day: '2-digit' });
有关toLocaleDateString
的更多信息,您可以在此处找到
您可以安装MOMMJS:
npm install moment --save
import * as moment from 'moment';
下一个使用时刻多个语言环境支持:
moment().format('LL');
提示:根据您的语言环境,您的格式更好:
moment().format('ll'); // 4 avr. 2018 for french locale <br>
moment().format('LL'); // April 4, 2018 for US English <br>
希望我帮忙!