简体   繁体   中英

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);
}

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.

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.

Get it in a Easy Way:

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

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.

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM