Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert string to time in android?

Tags:

android

time

I am getting string from voice(Speech to text). When i speak time it's display e.g. "530pm". I want to convert only time from string. e.g. "530pm" to 05:30 PM. How can i achieve this? Thanks in advance.

I try this code but not work

String s= "530 pm";
        SimpleDateFormat dateFormat = new SimpleDateFormat("hh:mm aa"); 
        try {
            Date date1 = dateFormat.parse(s);
            Log.e("Time", ""+date1);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            Log.e("Error", ""+e);
        }
like image 527
Jigar Shekh Avatar asked May 26 '14 10:05

Jigar Shekh


2 Answers

Read SimpleDateFormat documentation (parse&format methods and pattern syntax).

http://developer.android.com/reference/java/text/SimpleDateFormat.html

String time = "530pm";
SimpleDateFormat dateFormat = new SimpleDateFormat("hmmaa"); 
SimpleDateFormat dateFormat2 = new SimpleDateFormat("hh:mm aa");
try {
    Date date = dateFormat.parse(time);

    String out = dateFormat2.format(date);
    Log.e("Time", out);
} catch (ParseException e) {
}
like image 153
Dario Avatar answered Nov 08 '22 00:11

Dario


final String NEW_FORMAT = " hh:mm";
final String OLD_FORMAT = "hh:mm:ss";
 String formatDate;
SimpleDateFormat sdf = new SimpleDateFormat(OLD_FORMAT);
            Date d = null;
            try {
                d = sdf.parse(Value);
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            sdf.applyPattern(NEW_FORMAT);
            formatDate=sdf.format(d);
like image 44
user3668424 Avatar answered Nov 08 '22 02:11

user3668424