百度时间是指百度搜索结果页面显示的搜索时间戳,通常以“刚刚”、“1小时前”等形式表达。而这些时间都是以北京时间为基准进行显示的。那么,如何从百度时间中解析出北京时间呢?本文将从以下多个方面作详细阐述,并提供代码示例。
一、解析思路
百度时间相对较为复杂,包括了今年、昨天、前天、3天前、4天前、一周前、两周前、三周前、1个月前、2个月前、3个月前等多种时间表示方式。为了从中解析出北京时间,我们需要先将其转化为一个时间戳,然后再将时间戳转化为北京时间。
二、解析过程
1. 时间戳转化
/** * 解析百度时间,获取时间戳 * createTime:2021-01-18-09:27:40 * author:Believe */ function parseBaiduTime(baiduTime) { var timestamp = ''; var now = new Date(); if (baiduTime == '刚刚') { timestamp = parseInt(now.getTime() / 1000); } else if (baiduTime.indexOf('秒前') != -1) { var second = parseInt(baiduTime); timestamp = parseInt(now.getTime() / 1000) - second; } else if (baiduTime.indexOf('分钟前') != -1) { var minute = parseInt(baiduTime); timestamp = parseInt(now.getTime() / 1000) - minute * 60; } else if (baiduTime.indexOf('小时前') != -1) { var hour = parseInt(baiduTime); timestamp = parseInt(now.getTime() / 1000) - hour * 60 * 60; } else if (baiduTime.indexOf('年') != -1) { timestamp = Date.parse(baiduTime.replace('年', '/').replace('月', '/').replace('日', '')) / 1000; } else { var date = new Date(); if (baiduTime.indexOf('昨天') != -1) { date.setDate(date.getDate() - 1); } else if (baiduTime.indexOf('前天') != -1) { date.setDate(date.getDate() - 2); } else if (baiduTime.indexOf('天前') != -1) { var day = parseInt(baiduTime); date.setDate(date.getDate() - day); } else if (baiduTime.indexOf('周前') != -1) { var week = parseInt(baiduTime); date.setDate(date.getDate() - week * 7); } else if (baiduTime.indexOf('月前') != -1) { var month = parseInt(baiduTime); date.setMonth(date.getMonth() - month); } timestamp = parseInt(date.getTime() / 1000); } return timestamp; }
2. 时间戳转化为北京时间
/** * 将时间戳转为北京时间 * time: 时间戳 * format: 时间格式,如'Y-m-d H:i:s' */ function timestampToBjTime(time, format) { var bjTime = ''; if (time == '') { // 如果时间戳为空,返回空串 return bjTime; } else { var date = new Date(parseInt(time) * 1000); date.setHours(date.getHours() + 8); bjTime = dateFormat(date, format); } return bjTime; }
三、代码示例
将上述两个函数结合起来,即可将百度时间解析为北京时间。
/** * 解析百度时间,返回北京时间 * baiduTime:百度时间 * format:时间格式,如'Y-m-d H:i:s' */ function parseBaiduTimeToBjTime(baiduTime, format) { var timestamp = parseBaiduTime(baiduTime); // 获取时间戳 var bjTime = timestampToBjTime(timestamp, format); // 转化为北京时间 return bjTime; }
四、小结
通过上述函数的代码示例,我们可以轻松地将百度时间解析为北京时间。这对于很多需要对搜索结果中的时间信息进行统计、展示和分析等工作的应用程序来说,会非常有帮助。