undefinedfix
Sign in

Ask a requirement JS how to judge whether the timestamp belongs to the same day

Fastful edited in Wed, 25 Jan 2023

In addhislist, how should if be divided and judged according to the day, and finally render the effect of the figure below? Do you have any ideas? thank you

function addHisList(obj) {
    var dom = '';
    if(...){
        dom += '<div>' + changeTime(obj.date,true) + '</div>';//日期
    }
    
    dom += '<div>' + obj.SName + '</div>';
    dom += '<div>' + obj.content + '</div>';
    return dom;
}

//渲染列表的地方
for (...) {
    changelookDom += addHisList(history[i])
}

//数据源
history = [
    {"type":"text","date":1592889320877,"SName":"xxx","content":"1"},
    {"type":"text","date":1592889320877,"SName":"xxx","content":"2"},
    {"type":"text","date":1592889320877,"SName":"xxx","content":"3"}, 
    {"type":"text","date":1592889320877,"SName":"xxx","content":"4"}
]
6 Replies
GeorgeP
commented on Wed, 25 Jan 2023

First of all, you need to make sure that your time information is added in order by default, so that you can have the following processing. Second, you need an upper level static variable or global variable to store the last time

General logic (excluding the upper lastdatestr variable)

function getDateStr(Mdate){
  let mdate=new Date(Mdate);
  return ( ( mdate.toLocaleDateString() ).replace(/\//g,"-") );
}
function addHisList(obj) {
    var dom = '';
    cDateStr= getDateStr( obj.date)
    if(cDateStr!=lastDateStr){
        dom += '<div>' + changeTime(obj.date,true) + '</div>';//日期
        lastDateStr=cDateStr;
    }
    
    dom += '<div>' + obj.SName + '</div>';
    dom += '<div>' + obj.content + '</div>';
    return dom;
}
fun88comthailand
commented on Wed, 25 Jan 2023

The idea is to process the history array into a same date in the same array member, and then adjust the addhislist function to link the demo https://codepen.io/liangxh052...

function handleHistory(history) {
  const arr = history.map(item => {
    return {
        date: dateFormat(item.date, 'YYYY-MM-DD'),
        list: [
            {
                SName: item.SName,
                content: item.content
            }
        ]
    }
  });
  let result = [];
  arr.forEach(item => {
    if (result.some(every => every.date === item.date)) {
        result.forEach(_ => {
          if(_.date === item.date) {
            _.list = _.list.concat(item.list)
          }
        })
    } else {
        result.push(item)
    }
})
  return result;
}

const history = [
    {"type":"text","date":1592889320877,"SName":"xxx","content":"1"},
    {"type":"text","date":1592889320877,"SName":"xxx","content":"2"},
    {"type":"text","date":1592889320877,"SName":"xxx","content":"3"}, 
    {"type":"text","date":1592889320877,"SName":"xxx","content":"4"},
    {"type":"text","date":1592981108862,"SName":"xxx","content":"4"}
]

console.log(handleHistory(history))


function dateFormat (date, format, en) {
    let self = new Date(date);
    let fmt = format || 'YYYY-MM-DD hh:mm:ss';
    let o = {
        'M+': self.getMonth() + 1,
        'D+': self.getDate(),
        'h+': self.getHours(),
        'H+': self.getHours() % 12 === 0 ? 12 : self.getHours() % 12,
        'N': self.getHours() >= 12 ? (en ? 'PM' : '\u4e0b') : (en ? 'AM' : '\u4e0a'),
        'm+': self.getMinutes(),
        's+': self.getSeconds(),
        'q+': Math.floor((self.getMonth() + 3) / 3),
        'S': self.getMilliseconds()
    };
    if (/(Y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (self.getFullYear() + '').substr(4 - RegExp.$1.length));
    }
    for (let k in o) {
        if (new RegExp('(' + k + ')').test(fmt)) {
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)));
        }
    }
    let week = ['\u65e5', '\u4e00', '\u4e8c', '\u4e09', '\u56db', '\u4e94', '\u516d'];
    let weekEn = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
    if (/(d+)/.test(fmt)) {
        if (en) {
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length > 1) ? weekEn[self.getDay()].substr(0, 3) : weekEn[self.getDay()]);
        } else {
            fmt = fmt.replace(RegExp.$1, ((RegExp.$1.length > 1) ? (RegExp.$1.length > 2 ? '\u661f\u671f' : '\u5468') : '') + week[self.getDay()]);
        }
    }
    return fmt;
};
Rad0o95
commented on Wed, 25 Jan 2023

Simple point is to see the month and day are equal to divide chant, write a format function into month and day string, compare whether the string is equal.

codewizzard
commented on Wed, 25 Jan 2023
// 假设时间是:2020-06-24 12:00:00
// 假设已经有转格式的方法,或者你用 momentJS 吧
// 准备的方法:比较从今天开始到结束的分秒时
const DATETIME = '2020-06-24 12:00:00';
const today = new Date().format('YYYY-MM-DD 00:00:00');
const todayStart = new Date(today).getTime();
const dateTime = new Date(DATETIME).getTime();

return dateTime > todayStart && dateTime < todayStart + 24 * 60 * 60 * 1000
MaveDev
commented on Wed, 25 Jan 2023

Convert to date, clear hours, minutes, seconds and milliseconds, and then compare them directly.

var timestamp1 = new Date('2020/05/10 12:34:56') * 1 // 1589085296000
var timestamp2 = new Date('2020/05/10 10:20:30') * 1 // 1589077230000
var result = new Date(timestamp1).setHours(0, 0, 0, 0) === new Date(timestamp2).setHours(0, 0, 0, 0)
goutham2027
commented on Thu, 26 Jan 2023
<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8" />
    <title>the final project</title>
    <style>
    </style>
</head>

<body class="bkgimg">
    <div id="doc">

    </div>
</body>
<script>
    var dok = document.getElementById('doc')
//数据源
    time = [
        {"type":"text","date":1592889320877,"SName":"xxx","content":"1"},
        {"type":"text","date":1592889320877,"SName":"xxx","content":"2"},
        {"type":"text","date":1592889320877,"SName":"xxx","content":"3"}, 
        {"type":"text","date":1592988177000,"SName":"xxx","content":"4"}
    ]
    var arr = []
    console.log(time)
    time.map(item=>{
        console.log('======',setTimes(item.date))
        let obj = {}
        obj.year = setTimes(item.date).years
        obj.mon = setTimes(item.date).mons
        obj.day = setTimes(item.date).days
        obj.time = setTimes(item.date).dds
        arr.push(obj)
        return
    })
    function unique5(array){
        var r = [];
        for(var i = 0, l = array.length; i < l; i++) {
            for(var j = i + 1; j < l; j++)
            if (array[i].year === array[j].year&&array[i].mon === array[j].mon&&array[i].day === array[j].day) j = ++i;
            r.push(array[i]);
        }
        return r;
    }

    console.log('这二十什么?',unique5(arr))
    unique5(arr).map(item=>{
        var div = document.createElement('div');
        div.innerHTML = `<div>${item.year+'-'+item.mon+'-'+item.day}</div>
        <div style="color:blue;padding-left:30px;line-height:60px">${item.time}</div>`
        dok.appendChild(div)
    })
    
    /*
     补零函数:toDB(num)
     参数:num数字
     返回值:小于10的补零返回

 */
function setDb(num) {
    //补零操作
    if (num < 10) {
        return '0' + num;
    } else {
        return '' + num;
    }
}

/*
     秒转成时间:xx天xx时xx分xx秒   :  -
     setTime(num)
         * 参数: 秒
         * 返回值: {}数据返回(灵活一点)
         
 */
function setTimes(timer) {
    var time = new Date(timer);
    var year = time.getFullYear();//年
    var mon = setDb(time.getMonth() + 1);//0 
    var day = setDb(time.getDate());//24
    var hour = setDb(time.getHours());//时
    var min = setDb(time.getMinutes());//分
    var sec = setDb(time.getSeconds());//秒
    var dd = year+'-'+mon+'-'+day+'-'+hour+':'+min+':'+sec
    return {
        dds:dd,
        years:year,
        mons:mon,
        days:day,

    }

}

</script>
</html>