-1

I want to compare two time based so i just convert time to date.

i have parse time like this:

 SimpleDateFormat h_mm_a = new SimpleDateFormat("h:mm a");
 Date d1 = h_mm_a.parse(txtTimeFrom.getText().toString());
 Date d2 =  h_mm_a.parse(txtTimeTo.getText().toString());
 if(d1.compareTo(d2)<0){
     ....................
 }
 else{
     Toast.makeText(ExecutiveRouteTracking.this,"Invalid Time",Toast.LENGTH_SHORT).show();
 }

It will throw exception like

java.text.ParseException: Unparseable date: “9:30 AM” (at offset 5)

Can any one help me to solve problem to compare two time?

Milap Pancholi
  • 134
  • 1
  • 12

1 Answers1

0

Try with Joda Time

    String currentTime = new SimpleDateFormat("HH:mm").format(new Date());

    DateTimeFormatter parseFormat = new DateTimeFormatterBuilder().appendPattern("HH:mm").toFormatter();

    LocalTime localTime = LocalTime.parse(currentTime, parseFormat);
    LocalTime limit = new LocalTime("14:00");
    return localTime.isAfter(limit);
Veeresh Charantimath
  • 4,641
  • 5
  • 27
  • 36
  • Will not work if OP has Java 7 or less – Akshay Jun 16 '17 at 11:18
  • 1
    @Akshay Since when is Joda limited to Java 8? – Tom Jun 16 '17 at 11:19
  • Oops...it is added in jdk 8..DateTimeFormatter class – Akshay Jun 16 '17 at 11:20
  • 1
    But Joda is not needed to parse a american format time... luckily Java can manage this itself. – AxelH Jun 16 '17 at 11:20
  • Joda-Time is an option. I believe there is a better one. The Joda-Time home page says “Users are now asked to migrate to `java.time` (JSR-310).” But is JSR-310 available in Android? Indeed! See [this question: How to use ThreeTenABP in Android Project](https://stackoverflow.com/questions/38922754/how-to-use-threetenabp-in-android-project), please. – Ole V.V. Jun 16 '17 at 18:52