Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java: Convert a string which represents a two digit year to four digits

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

like image 838
Ersen Osman Avatar asked Feb 15 '16 14:02

Ersen Osman


People also ask

How do you read 2-digit years?

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.

How do you convert a two digit year to a four digit year in Python?

The correct pattern to use is '%d-%b-%y' here, where %b matches an abbreviated month name.

What is a 4-digit year?

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").


1 Answers

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 the SimpleDateFormat instance is created. For example, using a pattern of "MM/dd/yy" and a SimpleDateFormat 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.

like image 141
songyuanyao Avatar answered Oct 07 '22 23:10

songyuanyao