Razoe Razoe - 1 year ago 121
Android Question

Android - String to Time(only) using Simple Date Format

So what i'm trying to do is basically, i have a String variable, and i'm trying to convert that string to a time format, so that i can then use that time to create an alert for that day.

For example.

String stringTime = "1:05 PM"

and i want to convert that to a date format so an alarm will be set to go off at the next 1:05PM.

When i try using the SimpleDateFormat, it shows up as a date and time, and the date is back in 1970. See code below.

Date[] date_formatted_times_A;
SimpleDateFormat formatter = new SimpleDateFormat("h:m a");

public Date[] DateConverterA (String[] times_A){

date_formatted_times_A = new Date[times_A.length];

for(int i=0;i<times_A.length;i++)
try {
date_formatted_times_A[i] = formatter.parse(times_A[i]);

} catch (java.text.ParseException e) {
return date_formatted_times_A;


But the result i get from this, in the case the string time is 1:05 PM is "Thu Jan 01 13:05:00 GMT 1970". I'm totally lost as to how i should proceed. Please remember i only want the time, and i need it to be in a way which i can then use to set an alarm with it after. The times will be stored in a DATE array (or what ever array you think is more suitable). 24hr or 12hr is fine!

Answer Source

Your Simple Date Format should be:
SimpleDateFormat formatter = new SimpleDateFormat(hh:mm a");

Try the following and learn different formats yourself:

try {
   SimpleDateFormat format = new SimpleDateFormat("hh:mm a"); //if 24 hour format
   // or
   SimpleDateFormat format = new SimpleDateFormat("HH:mm"); // 12 hour format
   java.util.Date d1 =(java.util.Date)format.parse(your_Time);
   java.sql.Time ppstime = new java.sql.Time(d1.getTime());
} catch(Exception e) {
   Log.e("Exception is ", e.toString());
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download