Paresh Mayani
Paresh Mayani

Reputation: 128448

Date format conversion using Java

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?

Upvotes: 6

Views: 7587

Answers (3)

Anonymous
Anonymous

Reputation: 86379

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

Upvotes: 1

locka
locka

Reputation: 6029

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.

Upvotes: 23

McStretch
McStretch

Reputation: 20675

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

Upvotes: 3

Related Questions