我正在尝试使用 datepicker 和 timepicker 对话框创建一个 unix 时间戳,但出现的问题是这一天总是差一分。例如,如果我选择 5 月 10 日,它将显示 5 月 11 日作为输出。然而,其他一切似乎都没有问题。任何建议都会很棒。
日期和时间选择器代码如下所示...
private DatePickerDialog.OnDateSetListener mDateSetListener =
new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year,
int monthOfYear, int dayOfMonth) {
mYear = year;
mMonth = monthOfYear;
mDay = dayOfMonth;
}
};
private TimePickerDialog.OnTimeSetListener mTimeSetListener =
new TimePickerDialog.OnTimeSetListener() {
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
mHour = hourOfDay;
mMinute = minute;
confirmDateChange();
}
};
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DATE_DIALOG_ID:
return new DatePickerDialog(this,
mDateSetListener,
mYear, mMonth, mDay);
case TIME_DIALOG_ID:
return new TimePickerDialog(this,
mTimeSetListener, mHour, mMinute, false);
}
return null;
}
接下来我调用它来获取时间戳
private long componentTimeToTimestamp(int year, int month, int day, int hour, int minute) {
Calendar c = Calendar.getInstance();
c.set(Calendar.YEAR, year);
c.set(Calendar.MONTH, month);
c.set(Calendar.DAY_OF_MONTH, day);
c.set(Calendar.HOUR, hour);
c.set(Calendar.MINUTE, minute);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MILLISECOND, 0);
return (c.getTimeInMillis()/1000L);
}
最后,这在 textview 中设置了值,但就像我说的那样,一个月中的某一天总是偏离一个
long mydate = componentTimeToTimestamp(mYear, mMonth, mDay, mHour, mMinute);
long datemod = mydate * 1000;
final java.util.Date d = new java.util.Date(datemod);
details.setText(d.toLocaleString());