I wish to remove the Joda-Time library from my project.
I am trying to convert a two digit year to full year. The following code from Joda-Time can fulfil the purpos
java.time
doesn’t supply default values for month and day of month the way it seems that Joda-Time does. The message says that it cannot obtain a LocalDate
from a year alone, or conversely, it is missing month and day (you may supply your own default values, though, as demonstrated in Mikhail Kholodkov’s answer). Generally this behaviour is here to help us: it reminds us to supply all the values needed, and makes it clear from the code if any default values are used, and which.
Just use the Year
class of java.time
. First declare
public static final DateTimeFormatter TWO_YEAR_FORMATTER = new DateTimeFormatterBuilder()
.appendValueReduced(ChronoField.YEAR, 2, 2, 1950)
.toFormatter();
Then use
int year = Year.parse("99", TWO_YEAR_FORMATTER).getValue();
System.out.println(year);
Output
1999
Insert your desired base value where I put 1950 to specify a year within 99 years (inclusive) from that year. If you want the year to be in the past including this year, you may use:
private static final Year base = Year.now(ZoneId.of("Asia/Kolkata")).minusYears(99);
public static final DateTimeFormatter TWO_YEAR_FORMATTER = new DateTimeFormatterBuilder()
.appendValueReduced(ChronoField.YEAR, 2, 2, base.getValue())
.toFormatter();
BTW, don’t take my word for it, but I think Joda-Time uses current year minus 30 years as base or pivot. If this is so, using 30 instead of 99 in the last snippet will be the most compatible (so will also give you the 1999 you expected).