Question

I am having a string that returns both date and time from database as 2012-11-09 13:20:17. Now I need to take the time from the database string and show the time like 13:20:17 pm if the phone time settings is 24 hour and if the phone time settings is 12 hour I should show it as 01:20:17 pm. The time format can be obtained by this line of code which shows whether its 24hr or 12hr

String timefrmt = Settings.System.getString(context.getContentResolver(),Settings.System.TIME_12_24);
SimpleDateFormat timesettingsFormat=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
date="2012-11-09 13:20:17";
Date myDate=null;
try {
     myDate=timesettingsFormat.parse(date);
} catch (ParseException e1) {
     // TODO Auto-generated catch block
     e1.printStackTrace();
} 
if(timefrmt==null){
     timefrmt="hh:mm aa";
}
SimpleDateFormat timeFormat=new SimpleDateFormat(timefrmt);
String time=timeFormat.format(myDate);

The sample code which I have tried is above but its crashing. Can anyone help me find a way for this. Thanks a lot

Was it helpful?

Solution

try this

public static String dateFormateNote(String date) 
{   

    try {
          DateFormat df1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
          DateFormat df2 = new SimpleDateFormat("hh:mm:ss");
          return df2.format(df1.parse(date));
        }
        catch (ParseException e) {
          return date;
        }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top