user2939293
user2939293

Reputation: 813

Java, change date format.

I want to change the format of date from yyyyMM to yyyy-MM.

I have found out that the two ways below works equally well. But which one is the best? I would prefer methodTwo since it is simplier, but is there any advantage using methodOne?

public String date;

public void methodOne()
{ 
    String newDate = date; 
    DateFormat formatter = new SimpleDateFormat("yyyyMM");
    DateFormat wantedFormat = new SimpleDateFormat("yyyy-MM");
    Date d = formatter.parse(newDate);
    newDate = wantedFormat.format(d);
    date = newDate;
}


public void methodTwo()
{
    date = date.substring(0, 4) + "-" + date.substring(4, 6);
}

Upvotes: 4

Views: 193

Answers (5)

Basil Bourque
Basil Bourque

Reputation: 340098

java.time.YearMonth

There is a third way: Use the YearMonth class built into Java 8 and later as part of the java.time framework.

You don't have a date and a time, so using a date-time class such as java.util.Date or even the java.time types (Instant, OffsetDateTime, ZonedDateTime) is not a good fit. As you have only a year and a month use, well, YearMonth – a perfect fit.

Rather than pass Strings around your code, pass these YearMonth values. Then you get type-safety and valid values.

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuuyy");
YearMonth ym = YearMonth.parse( input );

The default format used by the YearMonth::toString method uses the standard ISO 8601 format you desire.

String output = ym.toString();

Upvotes: 1

White Bullet
White Bullet

Reputation: 215

Using the SimpleDateFormat is the industry standard. It is easier to read and maintain in the future as it allows the format to be changed with ease.

Upvotes: 1

Santosh Jadi
Santosh Jadi

Reputation: 1525

Get it in a Easy Way:

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
String date = sdf.format(yourDate);

Upvotes: 1

randombee
randombee

Reputation: 719

I would say that methodOne is much more generic. If you need to change your wanted format again, you only have to change the argument "yyyy-MM" for whatever new format you want, no matter how exotic it is. I found that when you work with people all across the world, methodOne is much more useful and also easier to read than using substrings. Using substrings means that you have no way to make sure that what is coming has the format you expect. You could be splitting in the wrong order.

Upvotes: 3

eztam
eztam

Reputation: 3841

You should prefer method one because it can detect if the input date has an invalid format. Method two could lead to problems, when it's not guaranteed that the input date is always in the same format. Method one is also more easy to adjust, when you later want to change either the input or the output format.

It could make sense to use method two if performance really matters, because it should be slightly faster than method one.

Upvotes: 4

Related Questions