java - Get year format from a given Date format -


i have localized date format. want retrieve year format in java.

so if given mmddyyyy extract yyyy. if given mmddyy, extract yy.

i cannot find way info using simpledateformat, date, calendar etc. classes.

it's important note concept of "year format" applies simpledateformat. (in default jdk, anyway.) more specifically, simpledateformat dateformat implementation provided jdk uses concept of "format string" can pull out year format from; other implementations use more opaque mappings date string. reason, you're asking well-defined on simpledateformat class (again, among dateformat implementations available in stock jdk).

if you're working simpledateformat, though, can pull year format out regular expressions:

simpledateformat df=(something); final pattern year_pattern=pattern.compile("^(?:[^y']+|'(?:[^']|'')*')*(y+)"); matcher m=year_pattern.matcher(df.topattern()); string yearformat=m.find() ? m.group(1) : null; // if yearformat!=null, contains first year format. otherwise, there no year format in simpledateformat. 

the regular expression looks strange because has ignore y's happen in "fancy" quoted parts of date format string, "'today''s date 'yyyy-mm-dd". per comment in code above, note pulls out first year format. if need pull out multiple formats, you'll need use matcher little differently:

simpledateformat df=(something); final pattern year_pattern=pattern.compile("\\g(?:[^y']+|'(?:[^']|'')*')*(y+)"); matcher m=year_pattern.matcher(df.topattern()); int count=0; while(m.find()) {     string yearformat=m.group(1);     // here, yearformat contains count-th year format     count = count+1; } 

Comments

Popular posts from this blog

SPSS keyboard combination alters encoding -

Add new record to the table by click on the button in Microsoft Access -

javascript - jQuery .height() return 0 when visible but non-0 when hidden -