简体   繁体   中英

Representing week of year with Joda-Time

What is the best way to represent week of year with Joda-Time library? I'm looking something as elegant as YearMonth is for representing month of year.

After some searching I found solution using Partial class for this problem.

Partial yearWeek = new Partial(
                   new DateTimeFieldType[] {DateTimeFieldType.weekyear(), 
                                            DateTimeFieldType.weekOfWeekyear()}, 
                                            new int[] {year, week});

tl;dr

org.threeten.extra.YearWeek.of( 2018 , 28 ) 

java.time

The Joda-Time project is now in maintenance mode , with the team advising migration to the java.time classes.

org.threeten.extra.YearWeek

The java.time classes are extended by the ThreeTen-Extra project. This project includes the YearWeek class, just what you need.

Beware that "week" can have many definitions. The one used here is defined by the ISO 8601 standard, where the week # 1 contains the first Thursday of the calendar year, and Monday starts each week. So a year has either 52 or 53 weeks. A week-based year may contain a few days from the previous/succeeding calendar year around the end of December and beginning of January.

Pass the number of the week-based year, and the week number.

YearWeek yw = YearWeek.of( 2018 , 7 ) ;

Get a date within that week by specifying a day-of-week via the DayOfWeek enum.

LocalDate wednesdayOf2018W07 = yw.atDay( DayOfWeek.THURSDAY ) ;

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date , Calendar , & SimpleDateFormat .

The Joda-Time project, now in maintenance mode , advises migration to the java.time classes.

To learn more, see the Oracle Tutorial . And search Stack Overflow for many examples and explanations. Specification is JSR 310 .

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval , YearWeek , YearQuarter , and more .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM