Node: 将时间戳转换成日期并分组

// 对时间戳按日期进行分组
let moment = require('moment')


let timestamp_array = [
  1645059333000,
  1613523333000,
  1297904133000,
  1298076933000,
  1582073733000,
  1645318535000,
  1647389537000
]

let result = {}

for (let index in timestamp_array) {
  let timestamp = timestamp_array[index]
  let date = moment(timestamp).format("YYYY-MM-DD");
  // let date = moment(timestamp).format("YYYY-MM");

  // console.log(date);

  let date_split_array = date.split('-')
  // console.log(date_split_array);
  // 先判断年,之后判断月份
  let year = date_split_array[0]
  let month = date_split_array[1]

  let judge_year = result.hasOwnProperty(year)
  if (judge_year == false) {
    result[year] = {}
    // result[year][date] = data
    judge_month(year, month,date)
  } else {
    // result[year][date] = data
    judge_month(year, month,date)
  }

}
console.log(result);

function judge_month(year,month,date) {
  /*
    year: 字典中的年
    month: 
  */
  let judge_month = result[year].hasOwnProperty(month)
  if(judge_month == false){
    result[year][month] = {}
    result[year][month][date] = date
  }else{
    result[year][month][date] = date
  }

}

运行结果如下所示
image

posted @   胸怀丶若谷  阅读(286)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 百万级群聊的设计实践
· 永远不要相信用户的输入:从 SQL 注入攻防看输入验证的重要性
· 全网最简单!3分钟用满血DeepSeek R1开发一款AI智能客服,零代码轻松接入微信、公众号、小程
· .NET 10 首个预览版发布,跨平台开发与性能全面提升
· 《HelloGitHub》第 107 期
点击右上角即可分享
微信分享提示