-2

If i have an Array which contains the Strings 07:46:30 pm , 10:45:28 pm , 07:23:39 pm , .......

and I want to convert it into Time. How can i do this?

Sean Patrick Floyd
  • 292,901
  • 67
  • 465
  • 588
Chamal
  • 1,107
  • 6
  • 16
  • 23

5 Answers5

4

Here's how to convert an array of Strings in the given format to an array of dates:

public static Date[] toDateArray(final String[] dateStrings)
throws ParseException{
    final Date[] arr = new Date[dateStrings.length];
    int pos = 0;
    final DateFormat df = new SimpleDateFormat("K:mm:ss a");
    for(final String input : dateStrings){
        arr[pos++] = df.parse(input);
    }
    return arr;
}
Sean Patrick Floyd
  • 292,901
  • 67
  • 465
  • 588
3

Use the SimpleDateFormat class. Here is an example:

DateFormat formatter = new SimpleDateFormat("hh:mm:ss a");
for(String str : array){
    Date date = formatter.parse(str);
}
Jason
  • 1,226
  • 12
  • 23
2

Use the SimpleDateFormat class to parse the date.

jzd
  • 23,473
  • 9
  • 54
  • 76
1

You need to write your own parser. See this example:

http://www.kodejava.org/examples/101.html

michelemarcon
  • 23,277
  • 17
  • 52
  • 68
1

If you want a array or list of time...

String[] arrString = new String[] { "07:46:30 pm", "10:45:28 pm", "07:23:39 pm" }

Time[] arrTime = new Time[strArray.lengh];

or

List<Time> listTime = new ArrayList<Time>();

Array string to array or list time:

//For array
for (int i = 0; i < arrString.length; i++) {
   DateFormat formatter = new SimpleDateFormat("hh:mm:ss a");
   Date date = formatter.parse(arrString[i]);

   //Populate the ARRAY
   arrTime[i] = new Time(date.getTime());
}

//For list
for (String str : arrString) {
   DateFormat formatter = new SimpleDateFormat("hh:mm:ss a");
   Date date = formatter.parse(str);

   //Populate the LIST
   listTime.add(new Time(date.getTime()));
}
Renan
  • 741
  • 4
  • 7