我使用以下内容来获取一年中的一周.
SimpleDateFormat dateFormatforYearWeek = new SimpleDateFormat("yyyyww");
String s = dateFormatforYearWeek.format(date)
10月26日,我的价值为201444。然而,我希望它成为201443。我不知道如何将一年中的星期设置为0。有可能吗?如果不是,我如何修改它。
这是正确的方法吗?
int day = calendar.get(Calendar.DAY_OF_MONTH);
int year = calendar.get(Calendar.YEAR);
calendar.add(Calendar.WEEK_OF_YEAR, -1);
calendar.set(Calendar.DAY_OF_MONTH, day);
calendar.set(Calendar.YEAR, year);
SimpleDateFormat dateFormatforYearWeek = new SimpleDateFormat("yyyyww");
String s = dateFormatforYearWeek.format(date)
这篇文章可以帮助你:
为什么2010年12月31日返回1作为一年中的一周?
试试这样的sthg:
Calendar calDe = Calendar.getInstance(Locale.GERMAN);
我可能会按照以下方式进行:
SimpleDateFormat dateFormatForYear = new SimpleDateFormat("yyyy");
SimpleDateFormat yearWeekFormat = new SimpleDateFormat("w");
Integer weekFrom0 = Integer.valueOf(yearWeekFormat.format(date)) - 1;
String s = dateFormatForYear.format(date) + weekFrom0;
什么是一周
SimpleDateFormat
的文档未能定义它们所指的周的含义。其他消息来源表示,他们打算采用ISO 8601标准对周的定义。但他们违反了这一点,定义了calendar.getMinimalDaysInFirstWeek() == 1
而不是4,正如在另一个答案中所讨论的那样。
你在问题中所说的一年中的一周是什么意思?
ISO 8601
如上所述,ISO 8601将一年中的一周定义为从周一开始,其中第一周包含一年中第一个星期四。
本标准还定义了一种字符串格式来表示一年中的一周:YYYY-Www
或YYYYWww
。注意中间的W
。这封信很重要,因为它避免了年-月格式YYYY-MM
的歧义。如果可能的话,我建议你遵守ISO8601。
零周计数
我从没听说过从零开始数周。这对我来说毫无意义;我建议尽可能避免这种情况。
如果不可能,我建议你使用日期时间库来计算一年中的标准周,并减去一。但我确信这是一条糟糕的旅行之路。
时区
时区对于确定日期至关重要,因此对于确定一周也至关重要。在巴黎结束的午夜钟声敲响时,意味着法国新的一周,而在蒙特利尔仍然是"上周"。
Joda时间
Java中的旧date-tim类是出了名的麻烦、混乱和有缺陷:Java.util.date、Java.util.Calendar、Java.text.SimpleDateFormat。请避免它们。
相反,使用Joda Time或java 8中内置的java.Time包(灵感来自Joda Time)。
DateTime now = DateTime.now( DateTimeZone.forID( "America/Montreal" ) );
String output = ISODateTimeFormat.weekyearWeek().print( now );
运行时。
now: 2014-11-03T02:30:10.124-05:00
output: 2014-W45
如果你必须坚持零周数:
int zeroBasedWeekNumber = ( now.getWeekOfWeekyear() - 1 ) ;