在Angular中使用setDate为日期追加当前时间的问题
解决方案
核心思路
后端返回的2024-05-31是无时间信息的日期字符串,通过new Date()解析时会根据本地时区生成默认时间(比如你的场景中是05:30:00)。要替换为当前系统的实时时分秒,只需保留后端日期的年月日部分,将时间部分替换为当前系统的时间即可。
方法一:操作Date对象替换时间
直接修改后端日期的时分秒毫秒为当前系统时间:
// 获取后端返回的日期字符串 const backendDateStr = x.response.Date; const targetDate = new Date(backendDateStr); // 获取当前系统的实时时间参数 const now = new Date(); const currentHours = now.getHours(); const currentMinutes = now.getMinutes(); const currentSeconds = now.getSeconds(); const currentMs = now.getMilliseconds(); // 替换目标日期的时间部分 targetDate.setHours(currentHours, currentMinutes, currentSeconds, currentMs); // 用datePipe格式化 this.StartDate = this.datePipe.transform(targetDate, "yyyy-MM-dd HH:mm:ss");
方法二:字符串拼接后转换
拆分后端日期字符串,拼接当前系统时间后再格式化:
// 获取后端日期字符串 const backendDateStr = x.response.Date; const now = new Date(); // 格式化当前系统时间为HH:mm:ss格式 const currentTime = `${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}:${now.getSeconds().toString().padStart(2, '0')}`; // 拼接完整日期字符串并转换为Date对象 const fullDate = new Date(`${backendDateStr} ${currentTime}`); // 用datePipe格式化 this.StartDate = this.datePipe.transform(fullDate, "yyyy-MM-dd HH:mm:ss");
两种方法都能让最终的StartDate保留后端返回的年月日,同时使用当前系统的实时时分秒,而非时区偏移生成的默认时间。
内容的提问来源于stack exchange,提问作者user3653474
相关产品推荐
相关产品推荐

