在java中有YYYYWW格式吗 [英] Is there YYYYWW Format in java
问题描述
标准格式
ISO 8601 标准定义了这样的一年。您可能需要查看维基百科文章此处和 here 作为指导,因为您的格式不太标准,不明确。该标准使用 W
和可选的连字符,例如 YYYY-Www
。
Joda-Time
Joda-Time图书馆对ISO 8601有很好的支持,包括周。请参阅 ISODateTimeFormat
类及其 weekYearWeek
方法。
请注意,时区是确定日期,因此确定一个星期至关重要。在巴黎结束的星期天午夜的中暑意味着在法国新的一周,而在蒙特利尔仍然是上周。
使用Joda-Time 2.5的示例代码。 >
DateTime now = DateTime.now(DateTimeZone.forID(America / Montreal));
String output = ISODateTimeFormat.weekyearWeek()。print(now);
int weekNumber = now.getWeekOfWeekyear();
运行时
输出:2014-W45
避免使用juDate
与Java捆绑在一起的java.util.Date和.Calendar和SimpleDateFormat类臭名昭着的麻烦避免他们使用Joda-Time或新的 java.time包装(由Joda-Time启发)。
Is there any way to use Date in Java with the format YYYYWW? There is week of month but is there any way to find week of the year?
Standard Format
The ISO 8601 standard defines such week-of-year. You may want to review the Wikipedia articles here and here for guidance, as your format is not quite standard and is ambiguous. The standard uses a W
and optionally a hyphen, such as YYYY-Www
.
Joda-Time
The Joda-Time library has good support for ISO 8601 including weeks. See the ISODateTimeFormat
class and its weekYearWeek
method amongst others.
Note that time zone is crucial in determining a date and therefore a week. At the stroke of midnight ending Sunday in Paris means a new week in France while still "last week" in Montréal.
Example code using Joda-Time 2.5.
DateTime now = DateTime.now( DateTimeZone.forID( "America/Montreal" ) );
String output = ISODateTimeFormat.weekyearWeek().print( now );
int weekNumber = now.getWeekOfWeekyear();
When run.
now: 2014-11-03T02:30:10.124-05:00
output: 2014-W45
Avoid j.u.Date
The java.util.Date and .Calendar and SimpleDateFormat classes bundled with Java are notoriously troublesome. Avoid them. Use either Joda-Time or the new java.time package in Java 8 (inspired by Joda-Time).
这篇关于在java中有YYYYWW格式吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!