1

I am trying to parse a String into a Calendar but right now I'm having problems at TimeZone: My code:

public static Calendar convertStringToFullDates(String dateString) {
    Calendar cal = Calendar.getInstance();
    SimpleDateFormat sdf = new SimpleDateFormat(PATTENT_FULL_DATE_FORMAT, Locale.US);
    try {
        cal.setTime(sdf.parse(dateString));
    } catch (ParseException e) {
        DebugLog.e(e.getLocalizedMessage());
    }
    return cal;
}

and String :

String str = "Fri May 11 00:00:00 ICT 2018";

and pattern:

private static final String PATTENT_FULL_DATE_FORMAT = "EEE MMM dd HH:mm:ss z yyyy";

I tried but it throws an exception like this:

Unparseable date: "Fri May 11 00:00:00 ICT 2018"

How to solve this problem?

Dharman
  • 30,962
  • 25
  • 85
  • 135
Thang
  • 409
  • 1
  • 6
  • 17

1 Answers1

1

The following code works for me:

public class Main {
    public static void main(String[] args) throws ParseException {
        String str = "Fri May 11 00:00:00 ICT 2018";
        final String PATTENT_FULL_DATE_FORMAT = "EEE MMM dd HH:mm:ss z yyyy";
        SimpleDateFormat sdf = new SimpleDateFormat(PATTENT_FULL_DATE_FORMAT, Locale.US);
        Date date = sdf.parse(str);
        System.out.println(date);
    }
}

Note that java.util date-time classes are outdated and error-prone and so is their formatting API, SimpleDateFormat. I suggest you should stop using them completely and switch to the modern date-time API.

If you are doing it for your Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.

Using the modern date-time API:

import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

public class Main {
    public static void main(String[] args) {
        String str = "Fri May 11 00:00:00 ICT 2018";
        final String PATTENT_FULL_DATE_FORMAT = "EEE MMM dd HH:mm:ss z yyyy";
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern(PATTENT_FULL_DATE_FORMAT, Locale.US);
        ZonedDateTime zdt = ZonedDateTime.parse(str, dtf);
        System.out.println(zdt);

        // Print the date-time in a custom format
        System.out.println(zdt.format(dtf));
    }
}

Output:

2018-05-11T00:00+07:00[Asia/Bangkok]
Fri May 11 00:00:00 ICT 2018

Learn more about the modern date-time API at Trail: Date Time.

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110