I have a problem changing the current time into milliseconds, the milliseconds shown one month before the set date and time. I know the computer starts the months at 0, how can I solve the problem? First, I transfer the date and the time into String
, then I convert the String
into date in SimpleDateFormat
, and then I convert the date into Long
.
For example: When the user enter the date "2018/2/14 11:18 "(AM), the date convert to long is "1515899940000" .
Here is my code:
private void setDateField() {
Calendar c = Calendar.getInstance();
int yy = c.get(Calendar.YEAR);
int mm = c.get(Calendar.MONTH);
int dd = c.get(Calendar.DAY_OF_MONTH);
c.set(Calendar.MONTH, mm);
c.set(Calendar.DAY_OF_MONTH, dd);
c.set(Calendar.YEAR, yy);
DatePickerDialog datePickerDialog = new DatePickerDialog(this,android.R.style.Theme_Holo_Light_Dialog ,new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker datePicker, int selectedYear, int selectedMonth, int selectedDate) {
year = selectedYear;
month = selectedMonth;
day = selectedDate;
date_time = year + "/" + (month + 1) + "/" + day;
timePicker();
}
},year, month, day);
datePickerDialog.getDatePicker().setMinDate(c.getTimeInMillis());
datePickerDialog.show();
}
private void timePicker(){
// Get Current Time
final Calendar c = Calendar.getInstance();
hours = c.get(Calendar.HOUR_OF_DAY);
minutes = c.get(Calendar.MINUTE);
// Launch Time Picker Dialog
TimePickerDialog timePickerDialog = new TimePickerDialog(this,android.R.style.Theme_Holo_Light_Dialog,new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker view, int hourOfDay,int minute) {
hours = hourOfDay;
minutes = minute;
string_date = date_time+" "+format(hours) + ":" +format(minutes) ;
addtime.setText(string_date);
Log.e("JEJEJEJE",string_date);
SimpleDateFormat f = new SimpleDateFormat("yyyy/mm/dd HH:mm");
try {
Date d = f.parse(string_date);
milliseconds = d.getTime();
Log.e("LONGGGGGGG", String.valueOf(milliseconds));
} catch (ParseException e) {
e.printStackTrace();
}
}
}, hours, minutes, true);
timePickerDialog.show();
}
See Question&Answers more detail:os