代码
getTime() {
// 给定的时间字符串
const timeString = '2024-08-14 10:24:17'
// 将时间字符串转换为Date对象
// 注意:由于Date构造函数可能无法直接解析这种格式,我们使用Date.parse()的一个替代方法
// 但实际上,现代JavaScript引擎通常能够直接解析这种格式的字符串(取决于具体的实现)
// 如果不能直接解析,你可能需要像之前那样使用replace来修改字符串
const date = new Date(timeString);
// 检查date是否有效(即它是否成功表示了一个日期)
if (!isNaN(date.getTime())) {
// 减去一秒
date.setSeconds(date.getSeconds() - 1);
// 将修改后的Date对象转换回字符串格式
// 这里我们使用自定义的格式,因为Date对象没有直接的方法来以特定格式输出日期时间
// 你可以根据需要调整格式
this.newTimeString = `${date.getFullYear()}-${('0' + (date.getMonth() + 1)).slice(-2)}-${('0' + date.getDate()).slice(-2)} ${('0' + date.getHours()).slice(-2)}:${('0' + date.getMinutes()).slice(-2)}:${('0' + date.getSeconds()).slice(-2)}`;
console.log(this.newTimeString); // 输出类似 "2024-08-14 10:24:16" 的字符串
} else {
console.error('Invalid date string');
}
},