HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Formatting MMyyyy to MMyy

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
formattingmmyyyymmyy

Problem

The following is my sample code:

String month = "09";

String year = "2014";

String monthYear = "092014";


The monthYear format is MMyyyy, I wish to format it to become MMyy. Thus, I am doing it as follows:

Method 1:

final SimpleDateFormat oriMonthYear = new SimpleDateFormat( "MMyyyy" );
final SimpleDateFormat changeMonthYear = new SimpleDateFormat( "MMyy" );

String newMonthYear = changeMonthYear.format( oriMonthYear.parse( month + year) );


This give me correct output, but I am not sure am I doing it by stupid way or not. I believe it should be another best practice and smart to way to do it.

Solution

We can use YearMonth in Java 8 or later like below:
YearMonth
.parse(yearMonth, DateTimeFormatter.ofPattern(MMYYYY))
.format(DateTimeFormatter.ofPattern(MMYY));

Context

StackExchange Code Review Q#78598, answer score: 2

Revisions (0)

No revisions yet.