0

I'm new in Android and Java development.

I have this day type "Fri Jan 27 00:00:00 GMT+00:00 1995". <-- (input)

I want to get "1995/27/01" <-- (output)

I'm using this code :

String inputPattern = "EEE MMM dd HH:mm:ss z yyyy";
String outputPattern = "yyyy-MM-dd";

SimpleDateFormat inputFormat = new SimpleDateFormat(inputPattern);
SimpleDateFormat outputFormat = new SimpleDateFormat(outputPattern);

Date date = inputFormat.parse("Fri Jan 27 00:00:00 GMT+00:00 1995");
String str = outputFormat.format(date);

but I get a ParseException.

Any idea why?

deHaar
  • 17,687
  • 10
  • 38
  • 51
  • 1
    Well, what does the exception message say? Also note that you do not specify a locale, which means it will use the default locale which is not what you want if your input is always english. – Joachim Sauer Oct 07 '20 at 11:18
  • Why do you use a `java.util.Date` here? Do you have to? I mean are you told to use it or are you working with a very low Java version? – deHaar Oct 07 '20 at 11:33

2 Answers2

3

If you were using java.time (available from Java 8), you could do it like this:

public static void main(String[] args) {
    // example input String
    String datetime = "Fri Jan 27 00:00:00 GMT+00:00 1995";
    // define a pattern that parses the format of the input String
    String inputPattern = "EEE MMM dd HH:mm:ss O uuuu";
    // define a formatter that uses this pattern for parsing the input
    DateTimeFormatter parser = DateTimeFormatter.ofPattern(inputPattern, Locale.ENGLISH);
    // use the formatter in order to parse a zone-aware object
    ZonedDateTime zdt = ZonedDateTime.parse(datetime, parser);
    // then output it in the built-in ISO format once,
    System.out.println("date, time and zone (ISO):\t"
                        + zdt.format(DateTimeFormatter.ISO_ZONED_DATE_TIME));
    // then extract the date part
    LocalDate dateOnly = zdt.toLocalDate();
    // and output that date part using a formatter with a date-only pattern
    System.out.println("date only as desired:\t\t"
                        + dateOnly.format(DateTimeFormatter.ofPattern("uuuu/dd/MM")));
}

The output of this piece of code is

date, time and zone (ISO):  1995-01-27T00:00:00Z
date only as desired:       1995/27/01
deHaar
  • 17,687
  • 10
  • 38
  • 51
0

Maybe add applyPattern function in code

String inputPattern = "EEE MMM dd HH:mm:ss z yyyy";
String outputPattern = "yyyy-MM-dd";

SimpleDateFormat sdf = new SimpleDateFormat(inputPattern);
Date date = sdf.parse("Fri Jan 27 00:00:00 GMT+00:00 1995");

sdf.applyPattern(outputPattern);
String str = sdf.format(date);
Gung Eka
  • 33
  • 1
  • 6