Skip to content Skip to sidebar Skip to footer

Time Parsing Issue On Android

I am getting a parse exception when trying to parse the time string 02:22 p.m.. I have the following conversion function: public static long convertdatetotimestamp(String datestrin

Solution 1:

It so happens that a.m. and p.m. are called just this in Gaelic locale. At least on my Java 8. I am far from sure that it will be the case on (all) Android phones, but you may do some experiments with it.

Stringdatestring="02:22 p.m.";
LocaleparseLocale= Locale.forLanguageTag("ga");
DateTimeFormatteroriginalFormat= DateTimeFormatter.ofPattern("hh:mm a", parseLocale);
System.out.println(LocalTime.parse(datestring, originalFormat));

This prints

14:22

As Hugo so warmly and rightly recommends is his answer, I am using the modern Java date and time API, so you will need ThreeTenABP for the above code. See How to use ThreeTenABP in Android Project. Alternatively you may want to try the same locale with your otherwise outdated SimpleDateFormat.

US Spanish locale shows the same behaviour on my Java 8, so you may try that too: Locale.forLanguageTag("es-US").

Solution 2:

Following changes that i've made works fine for me.

publicstaticlongconvertdatetotimestamp(String datestring, String newdateformat, String olddateformat){
        DateFormatoriginalFormat=newSimpleDateFormat(olddateformat,Locale.ENGLISH);
        DateFormattargetFormat=newSimpleDateFormat(newdateformat,Locale.ENGLISH);
        Datedate=null;
        try {
            date = originalFormat.parse(datestring.replaceAll("\\.", ""));
            StringformattedDate= targetFormat.format(date);
            DateparsedDate= targetFormat.parse(formattedDate);
            longnowMilliseconds= parsedDate.getTime();

            return nowMilliseconds;
        } catch (ParseException e) {
            e.printStackTrace();
            return0;
        }

    }

Locale.ENGLISH you can use your locale, english solved my issue. Reference.

Thanks for responses and references.

Post a Comment for "Time Parsing Issue On Android"