UI5中后端/Date(...)格式Timestamp转dd/MM/yyyy失败求助
我之前也踩过微软这种旧JSON日期格式的坑,给你几个实用的解决方案,应该能解决你的问题:
方法1:自定义格式化器(最灵活快捷)
因为后端返回的/Date(1525521600000+0000)/是微软旧格式,并非UI5 OData类型默认支持的标准格式,所以直接用内置类型会解析失败。我们可以写一个自定义格式化函数来处理:
- 在控制器中添加格式化函数:
formatCustomDate: function(sRawDate) { if (!sRawDate) return ""; // 提取时间戳部分,兼容带时区偏移的格式 const timestampMatch = sRawDate.match(/Date\((\d+)([+-]\d{4})?\)/); if (!timestampMatch) return sRawDate; const timestamp = parseInt(timestampMatch[1], 10); const date = new Date(timestamp); // 格式化为dd/MM/yyyy const day = String(date.getDate()).padStart(2, '0'); const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始,需+1 const year = date.getFullYear(); return `${day}/${month}/${year}`; }
- 在XML视图中调用这个格式化器:
<Text text="{path: 'ValueDate', formatter: '.formatCustomDate'}" />
方法2:扩展UI5日期类型(适合全局复用)
如果你的应用多个地方都需要处理这种日期格式,可以扩展UI5的日期类型,实现全局复用:
- 创建自定义日期类型文件(比如
CustomDateType.js):
sap.ui.define([ "sap/ui/model/type/Date" ], function(DateType) { "use strict"; return DateType.extend("your.app.namespace.CustomDateType", { parseValue: function(oValue) { // 解析时处理微软旧格式 if (typeof oValue === "string" && oValue.startsWith("/Date(")) { const timestamp = parseInt(oValue.match(/Date\((\d+)\)/)[1], 10); return new Date(timestamp); } return DateType.prototype.parseValue.apply(this, arguments); }, formatValue: function(oValue, sTargetType) { // 统一格式化为dd/MM/yyyy if (oValue instanceof Date) { const day = String(oValue.getDate()).padStart(2, '0'); const month = String(oValue.getMonth() + 1).padStart(2, '0'); const year = oValue.getFullYear(); return `${day}/${month}/${year}`; } return DateType.prototype.formatValue.apply(this, arguments); } }); });
- 在XML视图中引入并使用:
<Text text="{ path: 'ValueDate', type: 'your.app.namespace.CustomDateType' }" />
为什么之前的尝试无效?
- 使用
sap.ui.model.odata.type.DateTime无输出:这个类型只支持标准OData日期时间格式(如2024-05-20T12:00:00Z),无法解析微软的/Date(...)格式,所以解析失败后输出为空。 - 使用
sap.ui.model.odata.type.Date不符合预期:同样,该类型不识别微软旧格式,会把原始字符串当作无效值错误解析,导致输出异常。
内容的提问来源于stack exchange,提问作者Penrock
相关产品推荐
相关产品推荐

