Date format conversion using Java

2020-01-29 16:22发布

I am having a date/time value in standard ISO 8601 format such as as 2010-07-26T11:37:52Z.

I want date in 26-jul-2010 (dd-mon-yyyy) format. How do I do it?

3条回答
爷、活的狠高调
2楼-- · 2020-01-29 16:47

Construct two SimpleDateFormat objects. The first you parse() the value from into a Date object, the second you use to turn the Date object back into a string, e.g.

try {
  DateFormat df1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
  DateFormat df2 = new SimpleDateFormat("dd-MMM-yyyy");
  return df2.format(df1.parse(input));
}
catch (ParseException e) {
  return null;
}

Parsing can throw a ParseException so you would need to catch and handle that.

查看更多
何必那么认真
3楼-- · 2020-01-29 16:51

I am providing the modern answer. No one should use SimpleDateFormat anymore.

java.time

Parsing text.

    String dateTimeValue = "2010-07-26T11:37:52Z";
    OffsetDateTime dateTime = OffsetDateTime.parse(dateTimeValue);

Generating text.

    DateTimeFormatter dateFormatter = 
        DateTimeFormatter.ofPattern(
            "dd-MMM-uuuu", 
            Locale.forLanguageTag("pt-BR")
        );
    String wantedFormattedDate = dateTime.format(dateFormatter);

Output:

    System.out.println(wantedFormattedDate);

26-jul-2010

The month abbreviation in the output depends on the locale provided (Brazilian Portuguese in my example).

I am exploiting the fact that your date-time is in ISO 8601 format, the format that the classes of java.time parse (and also print) as their default, that is, without any explicit formatter.

Avoid the SimpleDateFormat class used in the other answers. That class is notoriously troublesome and long outdated.

Normally you would not want to convert a date and time from a string in one format to a string in a different format. In your program keep date and time as a date-time object, for example Instant or OffsetDateTime. Only when you need to give out a string, format your date into one.

Links

查看更多
够拽才男人
4楼-- · 2020-01-29 16:52

Have you tried using Java's SimpleDateFormat class? It is included with the android SDK: http://developer.android.com/reference/java/text/SimpleDateFormat.html

查看更多
登录 后发表回答