我需要在不考虑时区的情况下将angular5中的String转换为Date对象
现在我正在使用
dateValue = new Date(dateValue );
此处的dateValue是来自服务的字符串,为 2016-01-05 当我将其转换为Date对象时,dateValue变为 2016年1月5日星期二05:30:00 GMT + 0530(印度标准时间)
通过忽略时区,转换为Date对象后,我需要具有相同的dateValue
答案 0 :(得分:0)
如果您打算在视图上呈现日期,则只需使用{{dateString |日期:'MM / dd / yyyy'}},如代码转换器所述。
但是,如果您想在component.ts中格式化日期,则可以在组件中导入DatePipe或FormatDate。
1)DatePipe:
import { DatePipe } from '@angular/common';
export class SampleComponent implements OnInit {
constructor(private datePipe: DatePipe) {}
transformDate(date) {
return this.datePipe.transform(date, 'yyyy-MM-dd');
}
}
不要忘记将DatePipe添加到模块中的提供程序。
providers: [DatePipe]
2)formatDate:
import { formatDate } from '@angular/common';
export class SampleComponent implements OnInit {
constructor(@Inject(LOCALE_ID) private locale: string) {}
transformDate(date) {
return formatDate(date, 'yyyy-MM-dd', this.locale);
}
}
答案 1 :(得分:0)
您可以使用DatePipe,
import { DatePipe } from '@angular/common'
.
.
export class AppComponent implements OnInit {
dateValue: string = "2016-01-05";
constructor(public datepipe: DatePipe) { }
ngOnInit(){
this.dateValue = this.datepipe.transform(new Date(this.dateValue),"yyyy-MM-dd");
}
}
如果使用DatePipe,则需要在应用程序模块中将DatePipe声明为提供程序。
import { DatePipe } from '@angular/common'
.
.
providers:[DatePipe]
这里是Demo
答案 2 :(得分:0)
也许您也可以尝试
dateInfo= '2019-01-30';
dateData = new Date(this.dateInfo);
this.dateData.toISOString().slice(0,10);
的堆叠闪电战
答案 3 :(得分:0)
这里您需要编写以下格式化日期的方法
使用以下方法,您可以获得格式化的日期字符串。
formatDate(date: Date): string {
return (""+ date.getFullYear() + "-" + date.getMonth() + 1 + "-" + date.getDate() )
}
在这里,您将忽略本地时间戳将字符串转换为Date。
getDate(date): Date {
var dateParts = date.split("-");
return new Date(Date.parse(this.stringDate));
}
答案 4 :(得分:0)
您可以按照建议使用日期管道来执行此操作。您也可以尝试一下以获得指定的结果。
dateValue = new Date(dateValue );
dateValue = moment(dateValue).format('YYYY-MM-DD');
如果您是新手,请查看this。它非常易于使用。
如果您正在使用npm,则只需运行以下命令:
npm install moment --save
只需将其导入到组件文件的顶部,如下所示:
import * as moment from 'moment';
现在您可以使用它了。
答案 5 :(得分:0)
您也可以尝试以下方法-
(?<=\.)\w+(?=\.)