280 lines
7.9 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import systemTime from '@ohos.systemDateTime';
import { timeSynchronization } from '../../api';
export function isSevenDaysAgo(date, days = 2) {
const today = new Date(); // 当前日期
const target = new Date(date); // 需要判断的日期
console.info("listFile succeed1", JSON.stringify(target));
const diff = today.getTime() - target.getTime(); // 计算两个日期之间的毫秒数差异
const diffDays = diff / (1000 * 60 * 60 * 24); // 将毫秒转换为天数
console.info("listFile succeed2", JSON.stringify(diffDays));
// 如果差异天数正好是2则原日期是当前日期的前2天
console.log('diffDays', diffDays, days)
return diffDays >= (Number(days));
}
// export async function writeLog(path,param){
// return
// const fileUtil = new FileUtil(globalThis.context)
// const date=dateFormat(new Date).split(' ')[0]
// const folderPath = await fileUtil.initFolder(`/${path}/${date}`);
// fileUtil.editFile(`${folderPath}/plcLog.txt`, JSON.stringify(param)+`\n`)
// }
///**时间格式化*/
//export function dateFormat(fmt, date) {
// var ret;
// const opt = {
// "y+": date.getFullYear().toString(), // 年
// "m+": (date.getMonth() + 1).toString(), // 月
// "d+": date.getDate().toString(), // 日
// "H+": date.getHours().toString(), // 时
// "M+": date.getMinutes().toString(), // 分
// "S+": date.getSeconds().toString() // 秒
// // 有其他格式化字符需求可以继续添加,必须转化成字符串
// };
// for (var k in opt) {
// ret = new RegExp("(" + k + ")").exec(fmt);
// if (ret) {
// fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
// };
// };
// return fmt;
//}
/**
* 日期不足两位补 0
*
* @param {string} value - 数据值
* @return {string} - 日期不足两位补 0
*/
function fill(value: number) {
return (value > 9 ? '' : '0') + value;
}
export function dateFormat(t) {
let year = t.getFullYear()
let month = t.getMonth() + 1
let day = t.getDate()
let hours = t.getHours()
let minutes = t.getMinutes()
let seconds = t.getSeconds()
return year + "-" + fill(month) + "-" + fill(day) + " " + fill(hours) + ":" + fill(minutes) + ":" + fill(seconds);
}
export function dateVersionFormat(t) {
let year = t.getFullYear()
let month = t.getMonth() + 1
let day = t.getDate()
let hours = t.getHours()
let minutes = t.getMinutes()
let seconds = t.getSeconds()
return year + "." + fill(month) + "." + fill(day) + "." + fill(hours);
}
//同步时时间
// export async function timeSynchronize() {
// let date = new Date();
// console.info('jiangsong1:timeSynchronization begin ');
//
// let params = {
// time: dateFormat(date),
// deviceNo: AppStorage.get('deviceNo'),
// version: AppStorage.get('baseInfo').version,
// judgeVersion: AppStorage.get('baseInfo').judgeVersion
// }
// let res: any = await timeSynchronization(params)
// res = res.timeSynchronizationRsp;
// AppStorage.setOrCreate('timeInfo', res.body)
//
//
// return res;
// }
// export async function setCurrentTime(): Promise<void> {
// let res = await timeSynchronize();
// let currentTime = res.head.time;
// let times = new Date(currentTime).getTime();
// console.log('jiangsong:times==' + times);
// try {
// await systemTime.setTime(times);
// // systemTime.setTime(times).then(() => {
// // console.info(`Succeeded in setting time.`);
// // }).catch((error) => {
// // console.info(`Failed to set time. message: ${error.message}, code: ${error.code}`);
// // });
// } catch (e) {
// console.info(`Failed to set time. message: ${e.message}, code: ${e.code}`);
// }
// }
enum timeType {
fulltime = 1
}
//获取当前时间并转化
export async function getCurrentTime(type?: timeType): Promise<string> {
const date = await systemTime.getDate();
const year = date.getFullYear();
let month = date.getMonth() + 1;
month = month < 10 ? '0' + month : month;
let dates = date.getDate();
dates = dates < 10 ? '0' + dates : dates;
let h = date.getHours();
h = h < 10 ? '0' + h : h;
let m = date.getMinutes();
m = m < 10 ? '0' + m : m;
let s = date.getSeconds();
s = s < 10 ? '0' + s : s;
if (type === 1) {
return `${year}${month}${dates}${h}${m}${s}`
} else {
return `${year}-${month}-${dates} ${h}:${m}:${s}`
}
}
//获取时分秒毫秒
export async function getCurrentHourTime(): Promise<string> {
const date = await systemTime.getDate();
const year = date.getFullYear();
let month = date.getMonth() + 1;
let h = date.getHours();
h = h < 10 ? '0' + h : h;
let m = date.getMinutes();
m = m < 10 ? '0' + m : m;
let s = date.getSeconds();
s = s < 10 ? '0' + s : s;
let ss = date.getMilliseconds();
let nowSS = ''
if (ss < 10) {
nowSS = '00' + ss
}
if (ss >= 10 && ss < 100) {
nowSS = '0' + s
}
return `${h}${m}${s}${nowSS || ss}`
}
//时间戳转日期
export function formatTime(time: number): string {
const h = parseInt(time / 3600)
const minute = parseInt(time / 60 % 60)
const second = Math.ceil(time % 60)
const hours = h < 10 ? '0' + h : h
const formatSecond = second > 59 ? 59 : second
return `${hours > 0 ? `${hours}:` : `${hours}:`}${minute < 10 ? '0' + minute : minute}:${formatSecond < 10 ?
'0' + formatSecond : formatSecond}`
}
// 根据指定个数分割数组
export function chunkArr(arr, size: number) {
//判断如果不是数组(就没有length)或者size没有传值size小于1就返回空数组
if (!arr.length || !size || size < 1) {
return []
}
let [start, end, result] = [null, null, []]
for (let i = 0; i < Math.ceil(arr.length / size); i++) {
start = i * size
end = start + size
result.push(arr.slice(start, end))
}
return result
}
//对象深拷贝
export function deepClone(target) {
// 如果是对象且不是原始值null
if (typeof target === 'object' && target !== 'null') {
// 创建容器
const result = Array.isArray(target) ? [] : {};
const keys = Object.keys(target); //注解二
// Object.keys()会过滤掉原型链上的属性
keys.forEach(key => {
result[key] = deepClone(target[key])
})
return result;
}
// 如果是原始值,则直接返回
return target;
}
export function stringToASC(str) {
const tempStr = str + '';
const strArr = tempStr.split('');
return strArr.map(str => str.charCodeAt())
}
export function fillZero(str, len) {
str = str + '';
if (str.length > len || !len) {
return str
}
let num = len - str.length;
let zeroStr = '';
for (var i = 0; i < num; i++) {
zeroStr = zeroStr + '0'
}
return zeroStr + str;
}
// 字符串转字节
export function string2Bytes(number, len) {
let str = (Math.floor(+number)).toString(2);
if (str.length > len) {
console.log('数据长度不对~~');
return
}
var byteString = fillZero(str, len);
var arrBytes = new Array();
for (var i = byteString.length; i > 0; ) {
let j = i - 8;
if (j < 0) {
j = 0
}
var s = byteString.slice(j, i);
var v = parseInt(s, 2);
arrBytes.push(v);
i = i - 8
}
return arrBytes;
}
//数组数据转字节
export function Array2Byte(array) {
var buf = new ArrayBuffer(array.length);
var view = new Uint8Array(buf);
for (var i = 0; i != array.length; ++i) {
view[i] = array[i] & 0xFF;
}
return view;
}
//经纬度转换
export function convertGpsCoord2(num) {
const tempNum = Math.floor(num);
const du = Math.floor(tempNum / 100);
const fen = tempNum % 100 + num - tempNum;
return du + fen / 60
}
export function debounce(fn, delay) {
// 利用闭包定义定时器id变量存储
let timer = null;
return () => {
// 如果有值就清除定时器,重新计时
if (timer) {
clearTimeout(timer)
}
timer = setTimeout(fn, delay);
}
}