Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java, change date format.

Tags:

java

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);
}
like image 466
user2939293 Avatar asked Dec 24 '22 09:12

user2939293


1 Answers

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.

like image 77
eztam Avatar answered Jan 10 '23 22:01

eztam