gpt4 book ai didi

java - Mongodb $week 和 Java Calendar.WEEK_OF_YEAR

转载 作者:可可西里 更新时间:2023-11-01 09:31:51 27 4
gpt4 key购买 nike

Mongodb 的 $week operator

Takes a date and returns the week of the year as a number between 0 and 53.

Weeks begin on Sundays, and week 1 begins with the first Sunday of the year. Days
preceding the first Sunday of the year are in week 0. This behavior is the same as the
“%U” operator to the strftime standard library function.

然而,Java 日历的 DAY_OF_WEEK 返回略有不同(美国区域设置)。例如,对于 2013 年,mongo 的第 1 周实际上是第 2 周。

我的问题是,任意添加 1 并不能解决问题。是否有一个公式可以用来确定使用哪个周数来获取周开始日期。

场景:我在 mongo 中运行一个聚合,返回一个周数。根据周数,我需要在周开始日期到达。

像下面这样的东西总是有效吗?假设日历是日历的另一个实例。

    Calendar firstDay = Calendar.getInstance(Locale.US);
firstDay.set(Calendar.DAY_OF_YEAR, 1);
int day = firstDay.get(Calendar.DAY_OF_WEEK);
if (day != Calendar.SUNDAY){
//both mongo and java calendar start in different weeks so add 1 to reconcile
calendar.set(Calendar.WEEK_OF_YEAR, number.intValue()+1);
}

最佳答案

我会完全避免将 Java 年度周纳入画面 - 除非你能以某种方式说服 MongoDB 不再如此崩溃。 (这是一个非常奇怪的一周的定义;我通常使用 ISO-8601 定义。)

如果您真的需要使用 java.util.Calendar 来实现这一点,您可能会使用类似这样的东西(未经测试):

// You really want to do all of this on a "date" basis, without DST messing
// things up...
Calendar firstDay = Calendar.getInstance(TimeZone.getTimeZone("UTC"), Locale.US);
firstDay.set(Calendar.DAY_OF_YEAR, 1);
while (firstDay.get(Calendar.DAY_OF_WEEK) != Calendar.SUNDAY) {
firstDay.add(Calendar.DAY, 1);
}

// firstDay is now at the start of week 1 from a mongodb perspective...
// We just need to add the number of weeks.
firstDay.add(Calendar.Day, (mongoWeekNumber - 1) * 7);

请注意,如果周数为 0,则一周的开始很容易在当前日历年之前的日历年中。

如果您有任何选择要使用的日期/时间 API,我强烈建议您使用 Joda Time 或 java.time 而不是 Calendar 虽然 - 然后您可以使用 LocalDate 来代替,并且有更清醒的时间。

关于java - Mongodb $week 和 Java Calendar.WEEK_OF_YEAR,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17479896/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com