1

When i pass argument as "09:30 AM" it returns exception in android shows Unparseable date: "09:30 AM" (at offset 6)

 public static String convertTo24Hour (String now){
        String time24="";
          try {
            SimpleDateFormat inFormat = new SimpleDateFormat("hh:mm a");
            SimpleDateFormat outFormat = new SimpleDateFormat("HH:mm");
            time24 = outFormat.format(inFormat.parse(now));
        } catch (Exception e) {
            System.out.println("Exception : " + e.getMessage());
        }
        return time24;
    }
  • 1
    Use a proper locale. – Tom Dec 29 '17 at 05:35
  • Are you sure you are not missing anything ? Cause code looks fine . try to assign Locale . – ADM Dec 29 '17 at 05:37
  • Code is correct, show complete exception log. – Navnath Godse Dec 29 '17 at 06:21
  • As an aside, even on Android consider throwing away the long outmoded and notoriously troublesome `SimpleDateFormat` and friends, and adding [ThreeTenABP](https://github.com/JakeWharton/ThreeTenABP) to your project in order to use `java.time`, the modern Java date and time API. It is so much nicer to work with. – Ole V.V. Dec 29 '17 at 07:08

1 Answers1

-1

try with this

public static String convertTo24Hour (String now){
    String time24="";
    try {
        SimpleDateFormat inFormat = new SimpleDateFormat("hh:mm a",Locale.getDefault());
        SimpleDateFormat outFormat = new SimpleDateFormat("H:mm", Locale.getDefault());
        time24 = outFormat.format(inFormat.parse(now));
    } catch (Exception e) {
        System.out.println("Exception : " + e.getMessage());
    }
    return time24;
}

change Locale based on your need. Hope this helps..

Nikhil Borad
  • 2,065
  • 16
  • 20
  • 1
    same exception :( – shamasudheen Dec 29 '17 at 05:44
  • How should that help? `SimpleDateFormat` already uses the default locale if you don't specify one. – Tom Dec 29 '17 at 05:44
  • @Tom i just put as default because i dont know his locale. he have to change based on his need. – Nikhil Borad Dec 29 '17 at 05:46
  • @shamasudheen i already try this code. and its working. just replace whole function with this. – Nikhil Borad Dec 29 '17 at 05:46
  • 1
    You obviously don't need his/her locale, you need to set a locale which accepts "am" as part of the date string (that _can_ be a fixed one). But let's assume you would know that, you should at least tell OP that he need to adjust that value. A "try with this" doesn't indicate that. – Tom Dec 29 '17 at 05:49