获取Joda时间一年的第一周的第一天的日期 [英] Get Date of the first day in the first week of a year in Joda Time

查看:1342
本文介绍了获取Joda时间一年的第一周的第一天的日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Java日期:tempDate = Sun Jan 01 00:00:00 GMT + 01:00 2012。



我想创建一个新的日期,这是tempDate年度第一周的第一天。



那就是:

  Mon Jan 02 00:00:00 GMT + 01:00 2012 

当我尝试使用Joda时间:

  DateTime cal = new DateTime(tempDate).withWeekOfWeekyear(1)。 
withDayOfWeek(DateTimeConstants.MONDAY);

我得到了我想要的,但在上一年:

  Mon Jan 03 00:00:00 GMT + 01:00 2011 

如何在Joda时间做这项工作?

解决方案

你必须了解a DateTime的年份和周年。



Joda-Time 根据 ISO 8601标准,星期一是本星期的第一天。然而,几年并不总是从星期一开始。
根据ISO标准,一年的第一周是包含当年第一个星期四的星期。
因此,一年的某些日子可能会下降到上一个或下一年的一周。



在您的示例中01/01/2012在事实这样的一天。它属于2011年的第52周。因此,其2012年与2011年(2011年)不同。
因此,如果将日期更改为其周年的第一周,您将获得 DateTime



为了使这项工作始终如一,您只需确保您的周年是与您的年份相同:

  DateTime onTheFirstDayOfTheFirstWeek = dateTime.withWeekyear(dateTime.getYear())withWeekOfWeekyear(1).withDayOfWeek 1); 

您的评论中的解决方法将无法正常工作,具体来说,系统会失败时间在与一周不同的一天中。


I have a Java date: tempDate = Sun Jan 01 00:00:00 GMT+01:00 2012.

I would like to create a new Date, that is the first day of the first week in the year of tempDate.

That is:

  Mon Jan 02 00:00:00 GMT+01:00 2012

When I try to use Joda Time:

DateTime cal = new DateTime(tempDate).withWeekOfWeekyear(1).
                     withDayOfWeek(DateTimeConstants.MONDAY);

I get what I want, but in the previous year:

Mon Jan 03 00:00:00 GMT+01:00 2011

How can I make this work in Joda Time?

解决方案

You must understand the difference between a DateTime's year and its week year.

In Joda-Time, in accordance with the ISO 8601 standard, Monday is the first day of the week. Yet years do not always start on a Monday. The first week of a year, still according to the ISO standard, is the week that contains the first Thursday of that year. As a consequence certain days of a year may fall into a week of the previous or the next year.

In your example 01/01/2012 is in fact such a day. It belongs to week 52 of 2011. So its year (2012) is different from its week year (2011). Consequently, if you change the date to the first week of its week year, you'll get a DateTime in the first week of 2011.

To make this work consistently you simply have to make sure your week year is the same as your year :

DateTime onTheFirstDayOfTheFirstWeek = dateTime.withWeekyear(dateTime.getYear()).withWeekOfWeekyear(1).withDayOfWeek(1);

BTW the workaround in your comment will not work consistently, specifically it will fail when the system time falls in a day that has a year different from it's week year.

这篇关于获取Joda时间一年的第一周的第一天的日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆