SimpleDateFormat 提前一天

SimpleDateFormat is one day ahead

我正在尝试显示 SimpleDateFormat 的日期。我的问题是,如果我正在格式化 31/08/2017,这是星期四(在法国),则显示为星期五。它每天都这样做。

我首先在 DatePickerDialog 中获取日期:

public class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener {

private OnPickerSet mListener;

@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    final Calendar c = Calendar.getInstance();
    int year = c.get(Calendar.YEAR);
    int month = c.get(Calendar.MONTH);
    int day = c.get(Calendar.DAY_OF_MONTH);

    return new DatePickerDialog(getActivity(), this, year, month, day);
}

public void onDateSet(DatePicker view, int year, int month, int day) {
    mListener.onDateSet(new Date(year,month,day));
}

public void setOnPickerSetListener(OnPickerSet listener) {
    mListener = listener;
}
}

日期

class Date extends java.util.Date {

SimpleDateFormat formatter = new SimpleDateFormat("EEE dd MMM", Locale.FRANCE);

public Date() {
    // I don't want it set here
}

public Date(int year, int month, int day) {
    super(year, month, day);
}

@Override
public String toString() {
    formatter.setTimeZone(TimeZone.getTimeZone("Europe/Paris"));
    return formatter.format(this);
}
}

我没有对我的日期进行任何计算,所以我不明白为什么?

首先你必须修改你的 Date class

的构造函数
super((year-1900), month, day);

有关此内容的更多信息,请参见 javadoc

其次,您必须从 toString 方法中删除行

formatter.setTimeZone(TimeZone.getTimeZone("Europe/Paris"));

第三,也是更重要的一点,放弃使用如此多已弃用的方法和构造函数扩展 class 的整个想法。您可以将格式代码放入实用程序 class 并使用方法 Calendar.getTime().

从日历中获取日期 class