Reputation: 123
How to get current date and time in android and insert into the mysql database... i am using EditText and trying to get the current date and time in it... but i cannot insert it... so anyone share your idea how to get current date and time in edittext and insert into mysql database...
Calendar calendar = Calendar.getInstance();
String currentdate = DateFormat.getDateInstance().format(calendar.getTime());
tname = (EditText) findViewById(R.id.name);
tname.setText(currentdate);
trying to get the date....
private void registerUser() {
String date =tname.getText().toString().trim().toLowerCase();
register(date);
}
Full code
public class MainActivity extends AppCompatActivity {
EditText tname;
Button button;
private static final String REGISTER_URL="http://192.168.0.106/test/checkin.php";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Calendar calendar = Calendar.getInstance();
String currentdate = DateFormat.getDateInstance().format(calendar.getTime());
tname = (EditText) findViewById(R.id.name);
tname.setText(currentdate);
button = (Button) findViewById(R.id.btn);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
registerUser();
}
});
}
private void registerUser() {
String date =tname.getText().toString().trim().toLowerCase();
register(date);
}
private void register(String date) {
String urlSuffix = "?date=" + date;
class RegisterUser extends AsyncTask<String, Void, String> {
ProgressDialog loading;
@Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(MainActivity.this, "Please Wait", null, true, true);
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
Toast.makeText(getApplicationContext(),"Registered", Toast.LENGTH_SHORT).show();
}
@Override
protected String doInBackground(String... params) {
String s = params[0];
BufferedReader bufferReader=null;
try {
URL url=new URL(REGISTER_URL+s);
HttpURLConnection con=(HttpURLConnection)url.openConnection();
bufferReader=new BufferedReader(new InputStreamReader(con.getInputStream()));
String result;
result=bufferReader.readLine();
return result;
}catch (Exception e){
return null;
}
}
}
RegisterUser ur=new RegisterUser();
ur.execute(urlSuffix);
}
}
Upvotes: 4
Views: 1751
Reputation: 1667
Try using java.sql.date like this :
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date myDate = formatter.parse(date);
java.sql.Date sqlDate = new java.sql.Date(myDate.getTime());
insert(sqlDate);
Upvotes: 1
Reputation: 261
try this code
// Parse the date
SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yyyy HH:mm");
Date selectedDate = sdf.parse("04-11-2018 01:10");
// then create the MySQL datetime string
sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateString = sdf.format(selectedDate);
Upvotes: 1