javascript 如何从node和mongodb中的date对象中删除时间

0md85ypi  于 2023-02-28  发布在  Java
关注(0)|答案(2)|浏览(110)

我尝试在mongo的聚合管道中应用基于日期的过滤器。请参见下面的聚合管道:

var projectQry = [
      {
        $match: {
          "prmid": userId
        }
      },
      {
        "$unwind": {
          path : '$performanceData'
        }
      },
      {
        $match: {
          performanceData.recharge_date": {
            $gte: fromDate, $lte: toDate
          }
        }
      },
      {
        $group : {
          _id: "$performanceData.campaign_name", 
          basecount: {
            $sum: "$performanceData.basecount"
          }
        }
      },
      {
        $project: {
          _id: 0,
          campaign_name: "$_id",
          basecount: 1
        }
      }
    ];

现在,我从下面的逻辑中获取fromDate和toDate,实际上,我试图从recharge_date字段中获取当月1日到12日之间的数据:

const date = new Date();
    var fromDate = new Date(`${date.getFullYear()}-${date.getMonth()+1}-${01}`);
    var toDate = new Date(`${date.getFullYear()}-${date.getMonth()+1}-${12}`);

但是,当我在控制台中打印fromDate和toDate时,它显示以下输出:

2023-02-21T18:30:00.000Z
2023-03-02T18:30:00.000Z

我不知道如何删除这个18:30:00.000时间,因为我得到了错误的日期,因为它是5小时30分钟后,我已经在fromDate和toDate中定义的时间。时区在这里发挥了一些作用。
我也尝试使用setHours(0,0,0,0),但没有成功。
提前感谢您的回复。

u4dcyp6a

u4dcyp6a1#

差异是由时区的日期时间偏移量造成的。您需要使用Date.UTC()创建日期,以获取UTC时间。
以下内容将说明差异:

// 27th February, 2023 (Local time)
const localDate = new Date(2023, 1, 27);
// will display in your local time
console.log(localDate.toISOString());
// 27th February, 2023 (UTC)
const utcDate = new Date(Date.UTC(2023, 1, 27));
// will display in UTC => time part of string will be all zeroes
console.log(utcDate.toISOString());

// date time offset
const offset = utcDate - localDate;
const offsetInSeconds = offset / 1000;
const offsetInMinutes = offsetInSeconds / 60;
const offsetInHours = offsetInMinutes / 60;
const remainingMinutes = offsetInMinutes % 60;
// For you (OP) this should be 5h 30min, but may vary for others based on their local time
console.log(`Offset: ${offsetInHours}h ${remainingMinutes}min`);
2q5ifsrm

2q5ifsrm2#

const date = new Date();
var fromDate = new Date(`${date.getFullYear()}-${date.getMonth()+1}-${02}`);
fromDate.setUTCHours(0,0,0,0);
var toDate = new Date(`${date.getFullYear()}-${date.getMonth()+1}-${13}`);
toDate.setUTCHours(0,0,0,0);

console.log(fromDate);
console.log(toDate);

这将打印:

2023-02-01T00:00:00.000Z
2023-02-12T00:00:00.000Z

setUTCHours()方法是我们需要使用的。

相关问题