品牌设计公司排行榜前十名,seo外包服务公司,青海高端网站建设公司,做淘客需要用的网站发布时间格式化工具函数
概述
本文档介绍了一套用于解析和格式化日期时间字符串的工具函数#xff0c;旨在提供一种简便的方法来处理日期和时间数据#xff0c;同时确保在不同设备和时区下的兼容性。
函数说明
parseDateString(dateString)
这个函数用于将一个符合特定格…发布时间格式化工具函数
概述
本文档介绍了一套用于解析和格式化日期时间字符串的工具函数旨在提供一种简便的方法来处理日期和时间数据同时确保在不同设备和时区下的兼容性。
函数说明
parseDateString(dateString)
这个函数用于将一个符合特定格式的日期字符串解析为一个 Date 对象。它首先使用正则表达式来验证输入的字符串是否符合 YYYY-MM-DD HH:MM:SS 的格式。如果匹配成功它会分别提取并转换年、月、日、时、分、秒的部分然后创建并返回一个 Date 对象。如果输入的字符串不符合预期格式函数将尝试直接使用 Date 对象的构造器来解析。
参数
dateString (String): 需要解析的日期时间字符串。
返回值
Date: 一个 Date 对象表示输入字符串的日期和时间。
示例
const date parseDateString(2024-05-06 12:34:56);
console.log(date); // 输出: Mon May 06 2024 12:34:56 GMT0800 (中国标准时间)formatPublishTime(createTime)
这个函数用于格式化发布时间使其更易于阅读。它首先检查传入的时间字符串是否存在如果不存在则返回空字符串。然后函数将当前时间转换为北京时间并计算与发布时间的时间差。根据时间差的不同函数将返回不同格式的时间表述。
参数
createTime (String): 发布时间的日期时间字符串。
返回值
String: 格式化后的发布时间字符串。
示例
const formattedTime formatPublishTime(2024-05-05 12:00:00);
console.log(formattedTime); // 输出: 昨天发布注意事项
parseDateString 函数假定输入的日期时间字符串格式严格遵循 YYYY-MM-DD HH:MM:SS。如果输入的格式不符合预期函数可能无法正确解析。formatPublishTime 函数在计算时间差时将当前时间转换为北京时间这可能会影响到不同时区的用户。函数中的日期格式化遵循了一定的逻辑但可能需要根据实际应用场景进行调整。
代码实现
以下是上述函数的具体实现代码
// 解析日期字符串为Date对象兼容iOS设备
function parseDateString(dateString) {const regex /^(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})$/;const match dateString.match(regex);if (match) {const year parseInt(match[1], 10);const month parseInt(match[2], 10) - 1;const day parseInt(match[3], 10);const hour parseInt(match[4], 10);const minute parseInt(match[5], 10);const second parseInt(match[6], 10);return new Date(year, month, day, hour, minute, second);}return new Date(dateString);
}// 格式化发布时间
export const formatPublishTime (createTime) {if (!createTime) {return ;}const currentTime new Date(new Date().getTime() (new Date().getTimezoneOffset() / 60 8) * 3600 * 1000);const publishTime parseDateString(createTime);const timeDiff Math.floor(currentTime - publishTime / 1000);const dayDiff Math.floor((currentTime.setHours(0, 0, 0, 0) - publishTime.setHours(0, 0, 0, 0)) / 1000 / 60 / 60 / 24);if (dayDiff 0) {if (timeDiff 60) {return ${timeDiff}秒前;} else if (timeDiff 3600) {const minutes Math.floor(timeDiff / 60);return ${minutes}分钟前;} else {const hours Math.floor(timeDiff / 3600);return ${hours}小时前;}} else if (dayDiff 1) {return 昨天发布;} else if (dayDiff 2) {return 前天发布;} else {const year publishTime.getFullYear();const month (0 (publishTime.getMonth() 1)).slice(-2);const day (0 publishTime.getDate()).slice(-2);return ${year}-${month}-${day};}
};结语
通过使用这些工具函数开发者可以更轻松地处理和展示日期时间信息为用户提供更准确和友好的时间表述。