4

hello I have date like..

String date="09:00 AM"

But I need 09:00:00

So I use following.

 String date="09:00 AM"  
 SimpleDateFormat f1 = new SimpleDateFormat("hh:mm:ss");
 Date d1= f1.parse(date);

But it give me parse exception.

Please help me to find this.

Thanks in advance.

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
Hardik Joshi
  • 9,477
  • 12
  • 61
  • 113

2 Answers2

8

That's not the correct format for parsing that date, you need something like:

"hh:mm a"

Once you have a date object, you can then use a different format to output it. The following code segment shows how:

import java.text.SimpleDateFormat;
import java.util.Date;

String date = "09:27 PM";

SimpleDateFormat h_mm_a   = new SimpleDateFormat("h:mm a");
SimpleDateFormat hh_mm_ss = new SimpleDateFormat("HH:mm:ss");

try {
    Date d1 = h_mm_a.parse(date);
    System.out.println (hh_mm_ss.format(d1));
} catch (Exception e) {
    e.printStackTrace();
}

This outputs:

21:27:00

as you would expect.

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
0
Date c = Calendar.getInstance().getTime();

//day of the month

//EEEE---full day name
//EEE- 3 chars of the day
SimpleDateFormat outFormat = new SimpleDateFormat("EEE");
String dayof_month = outFormat.format(c);

//date
//MMM--3 chars of month name
//MM--number of the month
SimpleDateFormat df = new SimpleDateFormat("dd-MMM-yyyy");
String formattedDate = df.format(c);

//time
//hh---12 hrs format
//HH---24 hrs format
// a stands for AM/PM
DateFormat date = new SimpleDateFormat("hh:mm:ss a");
String localTime = date.format(c);

login_date_text.setText(dayof_month +" , "+formattedDate);
login_time_text.setText(localTime);

Log.e("testing","date ==" +dayof_month +" , "+formattedDate);
Log.e("testing","time ==" +localTime);
Suraj Rao
  • 29,388
  • 11
  • 94
  • 103
Nalini
  • 1