You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

99 lines
2.8 KiB
JavaScript

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

// utils/DataPointCacheUtil.js
class DataPointCacheUtil {
// 定义常量 key
static CACHE_KEY = 'ET620_HEALTH_DATA_POINT';
/**
* 比较两个时间字符串
* @param {string} time1 - 当前时间
* @param {string} time2 - 缓存的时间
* @returns {number} true 大于, false 小于
*/
static compareDateTime(time1, time2) {
let currentTime = this.convertToTimestamp(time1);
let cacheTime = this.convertToTimestamp(time2);
// console.log("currentTime:",currentTime)
// console.log("cacheTime:",cacheTime)
console.log("对比结果:",currentTime > cacheTime)
return currentTime > cacheTime;
}
/**
* 将 yyyy-MM-dd-HH-mm 格式转换为时间戳
* @param {string} datetime - 时间字符串
* @returns {number} 时间戳(毫秒)
*/
static convertToTimestamp(datetime) {
const [year, month, day, hour, minute] = datetime.split('-').map(Number);
return new Date(year, month - 1, day, hour, minute).getTime();
}
/**
* 永久存储时间数据
* @param {string} key - 存储键名
* @param {string} datetime - 时间字符串,格式 yyyy-MM-dd-HH-mm
*/
static setDateTime(key, datetime) {
try {
// 验证时间格式
if (!/^\d{4}-\d{2}-\d{2}-\d{2}-\d{2}$/.test(datetime)) {
throw new Error('时间格式应为 yyyy-MM-dd-HH-mm');
}
// 获取已缓存的时间
const cacheDateTime = this.getDateTime(key);
// 如果缓存中没有时间,或者新时间大于缓存时间,则存储
if (cacheDateTime != null) {
if(this.compareDateTime(datetime, cacheDateTime)){
console.log("后续设置缓存成功:",datetime);
wx.setStorageSync(key, datetime);
return true;
}
} else {
console.log("首次设置缓存成功:",datetime);
// 使用同步API存储确保立即生效
wx.setStorageSync(key, datetime);
return true;
}
} catch (err) {
console.error('存储失败:', err);
return false;
}
}
/**
* 获取永久存储的时间数据
* @param {string} key - 存储键名
* @returns {string|null} 时间字符串或null
*/
static getDateTime(key) {
try {
const datetime = wx.getStorageSync(key);
console.log("获取缓存成功:",datetime);
// 二次验证数据格式
if (datetime && /^\d{4}-\d{2}-\d{2}-\d{2}-\d{2}$/.test(datetime)) {
return datetime;
}
return null;
} catch (err) {
return null;
}
}
/**
* 移除永久存储的数据
* @param {string} key - 存储键名
*/
static remove(key) {
try {
wx.removeStorageSync(key);
return true;
} catch (err) {
return false;
}
}
}
export default DataPointCacheUtil;