0

I have a string with contains date time retrieved from webservice in the form "2014-11-12 16:19:00" I need to extract only the time in 12 hr format AM or PM . I tried but not got desired result .

public Date validateBreakingNewsDateDate() throws Exception{                            
        Date date = null;
        String dtStart = "2014-11-12 16:19:00";  
        SimpleDateFormat  format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
        try {  
             date= format.parse(dtStart);  
            Log.e("date", "kardate "+date); 
        } catch (ParseException e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
        }   
        return date;
}
Karthik Kolanji
  • 165
  • 2
  • 17

4 Answers4

2

Try the following code snippet

SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy     hh:mm:ss a");
Don Chakkappan
  • 7,397
  • 5
  • 44
  • 59
0

pass your date to this function it will return time

   public String setTime(String date) {
    final String OLD_FORMAT = "yyyy-MM-dd HH:mm:ss";
    final String NEW_FORMAT = "h:mm a";

    String newDate = "";
    try {
SimpleDateFormat sdf = new SimpleDateFormat(OLD_FORMAT);
        Date d = sdf.parse(date);
        sdf.applyPattern(NEW_FORMAT);
        newDate = sdf.format(d);
    } catch (ParseException e) {
        // TODO: handle exception
    }
    return newDate;
}

example

 public String setTime(String date) {
    final String OLD_FORMAT = "yyyy-MM-dd HH:mm:ss";
    final String NEW_FORMAT = "h:mm a";

    String newDate = "";
    try {
        sdf = new SimpleDateFormat(OLD_FORMAT);
        Date d = sdf.parse("2014-11-12 16:19:00");
        sdf.applyPattern(NEW_FORMAT);
        newDate = sdf.format(d);
    } catch (ParseException e) {
        // TODO: handle exception
    }
    return newDate;
}

output=4:19 PM

Arun Antoney
  • 4,292
  • 2
  • 20
  • 26
0

try this...

DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = format.parse(dtStart);
String newstring = new SimpleDateFormat("hh:mm aa").format(date);
uday
  • 1,348
  • 12
  • 27
0

You can fetch 12 hour time using SimpleDateFormat as follows

Date date = null;
String dtStart = "2014-11-12 16:19:00";
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd KK:mm:ss");
try {
    date = format.parse(dtStart);
    Log.e("date", "kardate " + date);
    // here hh means hours in 12 hr format and a stands for AM/PM
    format = new SimpleDateFormat("hh:mm:ss a");
    String desiredTime= format.format(date);
    // You will get newDate 04:19:00 pm
    Log.e("date", "newDate " + desiredTime);
} catch (Exception e) {
    e.printStackTrace();
}

Hope it helps ツ

SilentKiller
  • 6,944
  • 6
  • 40
  • 75
SweetWisher ツ
  • 7,296
  • 2
  • 30
  • 74