Judge Judge - 9 months ago 29
Java Question

Parse string to data and retrive hours

I am try to convert this string "

2014-07-23 09:00:00"
into something like this
"9 PM"
. My code is:

public void printTime() {
String data = "2014-07-23 09:00:00";
SimpleDateFormat f1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.UK);
SimpleDateFormat f2 = new SimpleDateFormat("ha",Locale.UK);
Log.v(LOG, "Time is" + f2.format(f1.format(data)));
}


But have this error:

Caused by: java.lang.IllegalArgumentException
at java.text.DateFormat.format(DateFormat.java:365)
at java.text.Format.format(Format.java:93)
at launcher.alpentouch.com.myapplication.MainActivity.printTime(MainActivity.java:30)
at launcher.alpentouch.com.myapplication.MainActivity.onCreate(MainActivity.java:21)
at android.app.Activity.performCreate(Activity.java:5008)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084) 
at android.app.ActivityThread.access$600(ActivityThread.java:130) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195) 
at android.os.Handler.dispatchMessage(Handler.java:99) 
at android.os.Looper.loop(Looper.java:137) 
at android.app.ActivityThread.main(ActivityThread.java:4745) 
at java.lang.reflect.Method.invokeNative(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:511) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553) 
at dalvik.system.NativeStart.main(Native Method)


 

Answer Source

Well i tried this:

    public static void main(String[] args) {
 String dateString = "2014-07-23 09:00:00";
 SimpleDateFormat sdf = new SimpleDateFormat("dd-M-yyyy hh:mm:ss");
 try {
    Date date = sdf.parse(dateString);
    Calendar calendar   = Calendar.getInstance();
    calendar.setTime(date);
    System.out.println(calendar.get(Calendar.HOUR_OF_DAY) +" PM") ;
} catch (ParseException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}



   }

9 PM