按“上周”、“上个月”和“去年”过滤时间戳数组

时间:2021-02-08 09:50:32

标签: javascript arrays timestamp

我有一个时间戳和值数组,我将每个时间戳转换为日期。我有一些功能可以显示从最旧到最新的日期。我想根据今天的日期计算 last weeklast monthlast year

const myData = [
  {timestamp: 1382086394000, value: 200},
  {timestamp: 1382086394001, value: 200},
  {timestamp: 1232131231232, value: 300},
  {timestamp: 2131231241212, value: 400},
  {timestamp: 1234124124112, value: 285},
  {timestamp: 1251251251251, value: 123},
  {timestamp: 1241241241241, value: 512},
  {timestamp: 1241241241241, value: 124},
  {timestamp: 2312312123121, value: 600},
];

这是数组的样子,请记住我已经将时间戳转换为实际日期。

2 个答案:

答案 0 :(得分:0)

您可以为此使用 Moment.js manipulating functions,例如加法或减法。

let timestamp = 1382086394000; 
console.log(moment(timestamp )) // Moment<2013-10-18T08:53:14+00:00>

// this is date after a week from the given timestamp
console.log(moment(timestamp ).add(1, 'w')) // Moment<2013-10-25T08:53:14+00:00>

您可以通过相应地减去来获得上周、月份和年份。 Moment.js 会处理您可能遇到的所有边缘情况。

答案 1 :(得分:0)

您可以轻松计算去年(如果当前年份为 2021 年,则假设为 2020 年 1 月 1 日至 12 月 31 日的全年)和上个月(如果当前日期为 2 月,则假设为 1 月 1 日至 1 月 31 日的完整月份)和上周(至于您过去 7 天(包括今天)的评论如下。

我使用半开放时间间隔(即不包括期末),因此您不必创建像 23:59:59.999 这样的时间戳。因此,您最终必须与 < 进行比较。

使用 getMonth()-1getDate()-6 将利用日期对象构造函数中的内部计算。因此,例如 new Date(2021, 0, -3) 将创建 2020 年 12 月 28 日

let today = new Date();
console.log(today.toLocaleString());

let lastYearStart = new Date(today.getFullYear()-1, 0, 1);
let lastYearEnd = new Date(today.getFullYear(), 0, 1);

console.log(lastYearStart.toLocaleString());
console.log(lastYearEnd.toLocaleString());


let lastMonthEnd = new Date(today.getFullYear(), today.getMonth(), 1);
let lastMonthStart = new Date(lastMonthEnd.getFullYear(), lastMonthEnd.getMonth()-1, 1);

console.log(lastMonthStart.toLocaleString());
console.log(lastMonthEnd.toLocaleString());

let lastWeekStart = new Date(today.getFullYear(), today.getMonth(), today.getDate()-6);
let lastWeekEnd = new Date(today.getFullYear(), today.getMonth(), today.getDate()+1);

console.log(lastWeekStart.toLocaleString());
console.log(lastWeekEnd.toLocaleString());

const mydata = [
  {timestamp: 1382086394000, value: 200},
  {timestamp: 1382086394001, value: 200},
  {timestamp: 1232131231232, value: 300},
  {timestamp: 2131231241212, value: 400},
  {timestamp: 1234124124112, value: 285},
  {timestamp: 1251251251251, value: 123},
  {timestamp: 1241241241241, value: 512},
  {timestamp: 1241241241241, value: 124},
  {timestamp: 2312312123121, value: 600},
];

for (let d of mydata) {
  if (d.timestamp >= lastWeekStart.getTime() && d.timestamp < lastWeekEnd.getTime())
    console.log("last week");
  else if (d.timestamp >= lastMonthStart.getTime() && d.timestamp < lastMonthEnd.getTime())
    console.log("last month");
  else if (d.timestamp >= lastYearStart.getTime() && d.timestamp < lastYearEnd.getTime())
    console.log("last year");
}

当然,某个时间戳可能(取决于当前日期)是所有三个类别,上周,上个月,去年。如果应该能够将一个时间戳归入多个类别,您可能需要相应地调整分类(即仅使用 if 而不是 else if

相关问题