Java, change date format.

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

I found out that the two paths below work equally well. But which one is better? I would prefer the Two method as it is simpler, but are there any advantages with the One method?

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);
}
+4
source share
5 answers

You must choose one method because it can determine if the input date is in the wrong format. The second method can lead to problems when it is not guaranteed that the input date is always in the same format. Method one is also easier to adjust when you later want to change either the input or output format.

, , , 1.

+4

, methodOne . , "yyyy-MM" , , , . , , , One , . , , , , , . .

+3

:

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

SimpleDateFormat . , .

+1

java.time.YearMonth

: YearMonth, Java 8 java.time.

, -, java.util.Date java.time(Instant, OffsetDateTime, ZonedDateTime), . , , YearMonth - .

, , YearMonth. .

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

The default format used by the method YearMonth::toStringuses the standard ISO 8601 format.

String output = ym.toString();
+1
source

Source: https://habr.com/ru/post/1629531/


All Articles