我有一个以下面的格式从JSON解析的日期对象:
String date = getJsonDateFromServer();
Date result = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ").parse(date);
但我只对时间部分感兴趣(没有月,年,日等)。 所以我的问题是:如何在不丢失时区信息的情况下正确替换日期部分(月,年,日)?
我最终想做的是:
(1)解析两个日期(没有日期信息)。开始和结束时间
(2)检查另一个日期'dw'(带有日期信息)如果'dw'介于开始和结束的时间之间(1)
例如:
Date start = parse(18:00 +02:00);
Date end = parse(20:00 +02:00);
Date dw=new Date();
boolean inBetween = dw>= start && dw <= end;
怎么做?
/ UPDATE: 我通过这种方式实现了测试目的:
public boolean isActiveOn(Date date) {
Calendar toCheck = Calendar.getInstance();
toCheck.setTime(date);
Calendar cal_start = Calendar.getInstance();
cal_start.setTime(this.time_begin);
cal_start.set(toCheck.get(Calendar.YEAR), toCheck.get(Calendar.MONTH),
toCheck.get(Calendar.DAY_OF_MONTH));
Calendar cal_end = Calendar.getInstance();
cal_end.setTime(this.time_end);
cal_end.set(toCheck.get(Calendar.YEAR), toCheck.get(Calendar.MONTH),
toCheck.get(Calendar.DAY_OF_MONTH));
boolean after_start = toCheck.after(cal_start);
boolean before_end = toCheck.before(cal_end);
return after_start && before_end;
}
但是,当在this.time_begin,this.time_end和date中设置不同的时区时,这不会导致问题吗?
答案 0 :(得分:1)
您所要做的就是:
String date = getJsonDateFromServer();
Date result = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ").parse(date);
SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ssZ")
Date timeOnly = dateFormat.parse(dateFormat.format(result));
现在您只有时间和时区的日期。
以下是比较代码:
Date start = dateFormat.format(result);
Date end = dateFormat.format(resultNr2);
Date dw = dateFormat.format(resultNr3);
boolean inBetween = dw.after(start) && dw.before(end);
答案 1 :(得分:0)
private DatePickerDialog createDialogWithoutDateField(){
Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
(AdditionalRepaymentDetailClass.this, datePickerListener_edtToDate,mYear,mMonth, mDay);
DatePickerDialog edtToDate= new DatePickerDialog(DirectDebitClass.this, datePickerListener_edtToDate, year, month,day);
try{
Field[] datePickerDialogFields = edtToDate.getClass().getDeclaredFields();
for (Field datePickerDialogField : datePickerDialogFields) {
if (datePickerDialogField.getName().equals("mDatePicker")|| datePickerDialogField.getName().equals("mDaySpinner")) {
datePickerDialogField.setAccessible(true);
DatePicker datePicker = (DatePicker) datePickerDialogField.get(edtToDate);
Field datePickerFields[] = datePickerDialogField.getType().getDeclaredFields();
for (Field datePickerField : datePickerFields) {
if ("mDayPicker".equals(datePickerField.getName())|| "mDaySpinner".equals(datePickerField.getName())) {
datePickerField.setAccessible(true);
Object dayPicker = new Object();
dayPicker = datePickerField.get(datePicker);
((View) dayPicker).setVisibility(View.GONE);
}
}
}
}
}catch(Exception ex){
}
return edtToDate;
}
你可以试试这个