Java library to support dates with limited precision (like year/month only)
Asked Answered
S

4

6

In some system I have to operate on dates which may have limited precission (like month and year only or year only), e.g. "2001" or "January 2011". I need to know not only date, but the presission (day, month or year) as well.

I can do this by hand, but does anybody know any java library which supports this type of dates with variable precission?

Sechrist answered 3/8, 2011 at 8:46 Comment(0)
A
2

I would consider using a well known library such as Joda Time and model each "date" as a time span (Interval in Joda Time).

After all, that's sort of what it is; "2001" is not actually a specific point in time, but a period.

The span / length of the interval would reveal the precision, and the starting point of the period could be interpreted as the point in time at which the "date occurred".

Arthromere answered 3/8, 2011 at 8:49 Comment(2)
It's not a period in the Joda sense ("2 months" or "3 week") - it's a partial, like YearMonth, LocalDate etc.Agretha
Aha. Not very experienced with the library. Thanks for clearing it up.Arthromere
P
2

java.time

In modern Java, use java.time classes defined in JSR 310, built into Java 8+.

Never use Date, Calendar, SimpleDateFormat, etc. Those terribly-flawed classes outside of the java.time package are legacy.

YearMonth

like month and year only

Use java.time.YearMonth. Construct with your choice of month number or Month enum.

YearMonth ym = YearMonth.of( 2025 , Month.JUNE ) ;

Year

or year only

Use java.time.Year.

Year y = Year.of( 2025 ) ;

LocalDate

not only date

For date-only, use LocalDate. No time-of-day, no time zone nor offset.

LocalDate ld = LocalDate.of( 2025 , Month.NOVEMBER , 17 ) ;
Pandich answered 11/10 at 23:41 Comment(0)
S
0

Lookup SimpleDateFormat and Date. These both classes should be sufficient for your use case.

Reference: SimpleDateFormat

Shirline answered 3/8, 2011 at 8:49 Comment(1)
Yep, but this is what I mean by 'by hand' - create class which has precision and date, and define all operations, using Calendar/Date/SimpleDateFormat. But before start I wanted to check - maybe someone did it already, and there is a good standard solution?Sechrist
A
0

Use Joda Time which already has support for a YearMonth type (amongst other things) - you can create your own Year type if you want, based on similar code.

Agretha answered 3/8, 2011 at 8:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.