Rozaimi Rozaimi - 14 days ago 4x
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:, 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(
at java.sql.Timestamp.valueOf(
at android.view.View.performClick(
at android.view.View$
at android.os.Handler.handleCallback(
at android.os.Handler.dispatchMessage(
at android.os.Looper.loop(
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(
at dalvik.system.NativeStart.main(Native Method)
Application terminated.


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) {

The line

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

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