-3

I have string inputs as "03:00 PM" or "09:00 AM", which i want to convert it to formatted time or even to integer. So that I can compare them by the order of time. Anyone can help me with that?

Thank you in advance.

  • 3
    What you have tried till now? – Amit Bera Feb 10 '18 at 06:08
  • I tried to create array of series of string time(from 9:00 AM to 7:00 PM). And then compare the input srtring to array and get position. But found it not smart and efficient, because there might be variety of time – Daulet Issatayev Feb 10 '18 at 06:12
  • @AmitBera do you any ideas? – Daulet Issatayev Feb 10 '18 at 06:22
  • 1
    Please search an research before posting. And you shall find. :-) – Ole V.V. Feb 10 '18 at 06:38
  • While it is a different question, I believe that this one should help: [SimpleDateFormat and not allowing it to go above 12 hours](https://stackoverflow.com/questions/43165422/simpledateformat-and-not-allowing-it-to-go-above-12-hours). – Ole V.V. Feb 10 '18 at 06:50

8 Answers8

2

Try this

import java.text.SimpleDateFormat;  
    import java.util.Date;  
    public class StringToDateExample1 {  
    public static void main(String[] args)throws Exception {  
        String sDate1="03:00 PM";  
        Date date1=new SimpleDateFormat("HH:mm").parse(sDate1);  

    }  
   }  
Sameera Sampath
  • 626
  • 1
  • 11
  • 20
  • 1
    Please don’t teach the young ones to use the long outdated and notoriously troublesome `SimpleDateFormat` class. At least not as the first option. And not without any reservation. Today we have so much better in [`java.time`, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). Yes, you can use it on Android. For older Android see [How to use ThreeTenABP in Android Project](https://stackoverflow.com/questions/38922754/how-to-use-threetenabp-in-android-project). – Ole V.V. Feb 10 '18 at 06:39
  • okay thanks for the advice appreciated. – Sameera Sampath Feb 10 '18 at 06:45
1

TL;DR

    DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("hh:mm a", Locale.ENGLISH);
    String input = "03:00 PM";
    LocalTime time = LocalTime.parse(input, inputFormatter);
    System.out.println(time);

This prints

15:00

Edit: Since your time format is in English, it may be considered cleaner to use this formatter instead:

    DateTimeFormatter inputFormatter
            = DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT)
                    .withLocale(Locale.ENGLISH);

It nearly matches. The latter formatter formats hours before 10 with only one digit, e.g., 5:12 AM, but also accepts two digits when parsing, so it works.

java.time

I recommend you use LocalTime from java.time for representing time of day, this is exactly what it is for. So it gives you good modelling and self-documenting code.

The other answers are correct but poor. While you should use library classes for your task, you should not use SimpleDateFormat and Date for at least three reasons. (1) They are long outdated and poorly designed; (2) DateFormat and SimpleDateFormat in particular are notoriously troublesome; (3) Date does not represent a time-of-day.

Comparing times

    LocalTime anotherTime = LocalTime.parse("09:00 AM", inputFormatter);
    if (anotherTime.isBefore(time)) {
        System.out.println("" + anotherTime + " comes before " + time);
    } else {
        System.out.println("" + time + " comes before " + anotherTime);
    }

This prints

09:00 comes before 15:00

Again, use LocalTime for comparison, it’s clearer than using formatted strings. Probably even better, LocalTime implements Comparable, so you can use Collections.sort() and other functions that rely on a natural ordering of objects.

If you do want a formatted string, the first option is LocalTime.toString():

    String formattedTime = time.toString();
    System.out.println(formattedTime);

This prints the same output as we got above, 15:00. If you want a different format, define a second DateTimeFormatter and use it in LocalTime.format().

Question: Can I use java.time on Android?

Yes, you can use java.time on Android. It just requires at least Java 6.

  • In Java 8 and later and on newer Android devices the modern API comes built-in.
  • In Java 6 and 7 get the ThreeTen Backport, the backport of the new classes (ThreeTen for JSR 310; see the links at the bottom).
  • On older Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages.

Links

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
0

You can use DateFormat. If you are sure that all is English, use Locale.ENGLISH.

static Date convertTimeString(String timeString) {

    try {
        return DateFormat.getTimeInstance(DateFormat.SHORT, Locale.ENGLISH)
                .parse(timeString);
    } catch(ParseException e) {
        Log.e("CONVERTDATE", "String \"" + timeString + "\" couldn't be parsed");
        return null;
    }
}
user9335240
  • 1,739
  • 1
  • 7
  • 14
0

The best way to do that.

  1. First get the string from (Edit Text or Whatever).
  2. Split the string into 2 part 1st time number and 'AM' or 'PM'
  3. Check whether the 2 digit is AM or PM so
  4. Check whether the string is AM or PM so if the string is PM add the numeric time with 12 you will get time in 24 hours format
007
  • 516
  • 1
  • 5
  • 17
0
SimpleDateFormat myFormat = new SimpleDateFormat("hh:mm a");
String time="09:00 AM";  
    try {

        Date date=myFormat.parse(time);
    } catch (ParseException e) {
        e.printStackTrace();
    }

On the date variable you will have your time

Elbek
  • 616
  • 1
  • 4
  • 15
0

This might not be a best solution. But what you can do is convert your input time to seconds and then compare integer values.

Below function can help you give an idea on getting seconds. (just a pseudo code. Not a tested one)

public int getSeconds(String timeValue){

String[] splitByColon = timeValue.split(":"); 
int hoursValue = Integer.parseInt(splitByColon[0])); 

String[] splitForMins = splitByColon[1].split(" "); 

if(splitForMins[1].equals("PM"))
{
hoursValue = hoursValue + 12; 
}

int minutesValue = Integer.parseInt(splitForMins[0]); 

return 3600*hoursValue + 60*minutesValue; 

}
G_S
  • 7,068
  • 2
  • 21
  • 51
0

You can try the below code:

String strTime = "03:00 pm";
SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm aa");
Date date = dateFormat.parse(strTime);
long time = date.getTime();
Amit Bera
  • 7,075
  • 1
  • 19
  • 42
0
import java.util.*;
import java.text.*;

public class DateDemo {

   public static void main(String args[]) {
      String time1="10:00 AM",time2="11:00 PM";
      DateFormat dfrmt = new SimpleDateFormat ("hh:mm a");
      Date Dtime1 =new Date();
      Date Dtime2 =new Date();
      try{
         Dtime1 = dfrmt.parse(time1);
         Dtime2 = dfrmt.parse(time2);
      }catch(Exception e){
      }

      if(Dtime1.compareTo(Dtime2)>0){
          //DTime1 comes after Dtime2
          System.out.println(dfrmt.format(Dtime1) + " > " + dfrmt.format(Dtime2));
      }else if(Dtime1.compareTo(Dtime2)<0){
          //Dtime1 Comes Before Dtime2
           System.out.println(dfrmt.format(Dtime1) + " < " + dfrmt.format(Dtime2));
      }
      else{
          //Equal   
          System.out.println(dfrmt.format(Dtime1) + " == " + dfrmt.format(Dtime2));
      }

 }
}

Try this to compare two dates; Create datetime object and use comapreTo() function

srx
  • 335
  • 1
  • 4
  • 17