Angular中如何将时间戳转为dd/MM/YYYY格式(Syncfusion Spreadsheet场景)
问题:Angular项目中Syncfusion Spreadsheet日期范围格式显示异常
需求是将时间戳转换为dd/MM/YYYY格式的日期,并在Syncfusion Spreadsheet的Q3单元格中显示类似29/11/2022 - 01/12/2022的日期范围,但当前实现后单元格显示的日期格式不符合预期。
原实现代码
export-electronic.component.ts
updatedata(){ this.dataApi.getElectronicById(this.id).subscribe(res => { this.electronicObj = res; console.log(this.electronicObj); this.spreadsheetObj.updateCell({ value: this.electronicObj.mantainence_history},"O3"); this.spreadsheetObj.updateCell({ value: this.electronicObj.cost_status},"P3"); this.spreadsheetObj.updateCell({ value: this.electronicObj.warranty_date.toDate()+this.electronicObj.expire_date.toDate()},"Q3");}
export-electronic.component.html
<ejs-spreadsheet #spreadsheet (created)="created()" (openComplete)="updatedata()" openUrl='https://ej2services.syncfusion.com/production/web-services/api/spreadsheet/open' allowOpen='true' (beforeSave)='beforeSave($event)' saveUrl='https://ej2services.syncfusion.com/production/web-services/api/spreadsheet/save' allowSave='true'> </ejs-spreadsheet>
问题分析与修正方案
原代码直接将两个Date对象拼接,会得到默认格式的日期字符串(如Wed Nov 29 2022...),无法满足dd/MM/YYYY的格式要求。
修正思路:使用toLocaleDateString('en-GB')将每个日期对象转换为dd/MM/YYYY格式的字符串,再拼接成需要的日期范围格式。
修正后的export-electronic.component.ts代码
updatedata(){ this.dataApi.getElectronicById(this.id).subscribe(res => { this.electronicObj = res; console.log(this.electronicObj); const q3Value = (new Date(this.electronicObj.warranty_date.toDate()).toLocaleDateString('en-GB')) + ' - ' + (new Date(this.electronicObj.expire_date.toDate()).toLocaleDateString('en-GB')); this.spreadsheetObj.updateCell({ value: this.electronicObj.mantainence_history},"O3"); this.spreadsheetObj.updateCell({ value: this.electronicObj.cost_status},"P3"); this.spreadsheetObj.updateCell({ value: q3Value},"Q3"); }); }
修正后,Q3单元格将正确显示dd/MM/YYYY - dd/MM/YYYY格式的日期范围。
内容的提问来源于stack exchange,提问作者Siripaiboon Flame Janpetch
相关产品推荐
相关产品推荐

