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);
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With