在java中有YYYYWW格式吗 [英] Is there YYYYWW Format in java

查看:1281
本文介绍了在java中有YYYYWW格式吗的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在Java中使用格式为YYYYWW的Date?

解决方案

标准格式



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屋!

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