This question has been asked many times but I have an issue which I feel makes it a unique question.
Here it goes.
I have a string which represents a two digit year i.e. to write 2016 I input 16
I have a requirement to convert a two digit year to four digit year i.e. 16 becomes 2016.
After going through some questions and answers I made the following findings
Solution 1
DateFormat sdfp = new SimpleDateFormat("dd.mm.yy");
Date d = sdfp.parse(input);
DateFormat sdff = new SimpleDateFormat("yyyy-MM-dd");
String date = sdff.format(d);
This would be great but I do not have a month or day in my case just a year and I could not find a way to create a date object with just the year.
Solution 2
The above could be solved with a Calendar
object but it does not allow the input an of a two digit year for its year field.
Edit Forgot to mention I cannot use Joda-Time because I'm working on the Android platform and it would increase the size of my project for just this small use
The default windowing algorithm used is as follows: If a 2-digit year is moved to a 4-digit year, the century (1st 2 digits of the year) are chosen as follows: If the 2-digit year is greater than or equal to 40, the century used is 1900. In other words, 19 becomes the first 2 digits of the 4-digit year.
The correct pattern to use is '%d-%b-%y' here, where %b matches an abbreviated month name.
Four Digit Year Format means the format which represents all four digits of the calendar year. The first two digits represent the century and the last two digits represent the year within the century (e.g., the century and year nineteen hundred and ninety-six is represented by "1996").
Why not just remove the part of month and day from the format?
DateFormat sdfp = new SimpleDateFormat("yy");
Date d = sdfp.parse(input);
DateFormat sdff = new SimpleDateFormat("yyyy");
String date = sdff.format(d);
LIVE
Here is the rule about how SimpleDateFormat
interpret the abbreviated year. (bold by me)
For parsing with the abbreviated year pattern ("y" or "yy"),
SimpleDateFormat
must interpret the abbreviated year relative to some century. It does this by adjusting dates to be within 80 years before and 20 years after the time theSimpleDateFormat
instance is created. For example, using a pattern of "MM/dd/yy" and aSimpleDateFormat
instance created on Jan 1, 1997, the string "01/11/12" would be interpreted as Jan 11, 2012 while the string "05/04/64" would be interpreted as May 4, 1964.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With