SQL时间窗口相关的时间表达式语法_日志服务-阿里云帮助中心
按照一下规则实现一个输入表达式返回时间
/**
* sls 时间表达式解析
*/
const moment = require('moment')
class SlsScheduledParse {
constructor() {
}
/**
* 解析时间表达式字符串
* @param param
* @returns {[]} 返回一个数组
*/
getParse(param){
let res = []
let regs = /^[1-9mh\@\+\-]*$/
if(param && regs.test(param)){
//先判断字符串中是否有别的字符串
for(let i=0;i<param.length;i++){
if(param[i]=='m' || param[i]=='h'){
if(res.length==0){
res.push(param.substr(res.length,i+1))
}else {
res.push(param.substr(res[res.length-1].length,i+1))
}
}
}
return res;
}else {
return res
}
}
/**
* 根据时间表达是获取到时间
* @param param
* @returns {string|null}
*/
getTime(param){
let arr = this.getParse(param)
if(arr.length==0){
return null
}
let now = moment()
for (let it of arr){
if(it.includes('m')){
if(it.includes('-')){
//减时间
let diff = it.substring(it.indexOf('-'),it.indexOf('m'))
if(diff.length==1){
diff = -1
}
now = now.add(diff,'minutes')
}else {
//加时间
let temp_str = it
if(it.includes('@')){
temp_str= it.replace('@','')
}
let diff = 1
if(temp_str.includes('+')){
diff = temp_str.substring(temp_str.indexOf('+'),temp_str.indexOf('m'))
}else {
diff = temp_str.substring(0,temp_str.indexOf('m'))
}
now = now.add(diff,'minutes')
}
if(it.includes('@')){
//分钟取整
now = now.startOf("minute")
}
}
if(it.includes('h')){
if(it.includes('-')){
//减时间
let diff = it.substring(it.indexOf('-'),it.indexOf('h'))
if(diff.length==1){
diff = -1
}
now = now.add(diff,'hours')
}else {
//加时间
let temp_str = it
if(it.includes('@')){
temp_str= it.replace('@','')
}
let diff = 1
if(temp_str.includes('+')){
diff = temp_str.substring(temp_str.indexOf('+'),temp_str.indexOf('h'))
}else {
diff = temp_str.substring(0,temp_str.indexOf('h'))
}
now = now.add(diff,'hours')
}
if(it.includes('@')){
//小时取整
now = now.startOf("hours")
}
}
}
return now.format('YYYY-MM-DD HH:mm:ss');
}
}
module.exports = SlsScheduledParse
let sls = new SlsScheduledParse();
let time = sls.getTime("24h+5m")
console.log(time)