Rozaimi Rozaimi - 1 month ago 13
Java Question

How to Cast value of TimeStamp datetime into mysql in android studio

I'm trying to cast/get the value of DatePickerDialog EditText "etDate" into mysql database. the datePickerDialog works fine(i can open it and select the date n display it in EditText).

And i declare it as below (The Timestamp is java.sql.Timestamp:)

final Timestamp datetime = Timestamp.valueOf(etDate.getText().toString());


Above code , i add it inside bRegister.setOnClickListener

the code shows no error and apps can run, but when i click on bRegister.setOnClickListener, it shows error as below.

E/AndroidRuntime: FATAL EXCEPTION: main
Process: my.com.rozaimi.datetime, PID: 15786
java.lang.IllegalArgumentException: Timestamp format must be yyyy-MM-dd HH:mm:ss.fffffffff; was '2016-10-6'
at java.sql.Timestamp.badTimestampString(Timestamp.java:507)
at java.sql.Timestamp.valueOf(Timestamp.java:414)
at my.com.rozaimi.datetime.MainActivity$2.onClick(MainActivity.java:62)
at android.view.View.performClick(View.java:4438)
at android.view.View$PerformClick.run(View.java:18422)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
Application terminated.

Answer

You are trying to parse a date string when a timestamp is expected, and the error output is pretty clear about this. One workaround would be to create a java.util.Date using your date string, then initialize a java.sql.Timestamp object using milliseconds since the epoch:

String dateString = etDate.getText().toString();
DateFormat df = new SimpleDateFormat("yyyy-MM-dd"); 
java.util.Date date;
try {
    date = df.parse(dateString);
    Timestamp datetime = new Timestamp(date.getTime());
} catch (ParseException e) {
    e.printStackTrace();
}

The line

Timestamp datetime = new Timestamp(date.getTime());

uses the constructor of java.sql.Timestamp to create a timestamp using milliseconds since the epoch.